Computers are good with numbers and mathematic functions. At times you might want the computer to perform some kind of calculation, for example 2 + 4 or 2 + 6 * 4. 2 + 4 is 6, but what about 2 + 6 * 4? well there are two answers to this: either 26 or 32.
Create a new C# project and name it MathOperations. Then type:
Console.WriteLine(2 + 6 * 4); Console.ReadLine();
Run it and you should get the answer 26, not 32. This is because C# will always do multiplication or division first. You can force the answer to be 32, in this case you put brackets around 2 + 6 so it should look like:
Console.WriteLine((2 + 6) * 4); Console.ReadLine();
This time write:
Console.WriteLine(6 / 3 * 4);
In this case we have division and multiplication, so which one does C# do first? Well in this case C# will start from the left, so the answer for this is 8 ( 6 / 3 = 2 and 2 * 4 = 8).
Short Hand Math
There is a much simpler way to do arithmetic. Instead of writing 2 + 6 * 4, comment out the above code except Console.ReadLine();. Then make a new integer variable called number.
int number = 5; number += 10; Console.WriteLine(number); Console.ReadLine();
You should get the result 15.
Instead of writing number = number + 5, we moved the addition operator to the left before the equal sign. You can do this for subtraction, multiplication and division.
Other Math Functions
You can also find the square root, power, sin, cos, and tan. For this we use the namespace system.math.
Let’s find the power of 2 and 6.
Console.WriteLine(Math.Pow (2, 6));
The result is 64. Next, let’s find the square root.
The result is 8.
There are many more functions that can be performed. For more information go to:
Performing basic and even complex arithmetic in C# is not difficult, because there are many functions available as demonstrated above. This tutorial covered the basics of adding and subtracting as well as order of calculations.