Basically, arithmetical operators (+, -, *, /) are the same as the mathematical ones. However, there are a few things to point out.
The most important thing to watch out is the kind of result you are expecting. If you will use two integers to perform a division, do not expect to get a real number, do not expect to get rounding, or any fractional part. For example, using integers, 7 / 2 = 3, not 4, not 3.5
Second thing to watch out about arithmetical operators when used with integer types is division by 0. Whenever you will try to divide an integer by 0, you will get a special kind of error, an exception called DivideByZeroException.
Next point, whenever you want to get the remainder of a division between two integers, use % operator. In math, 9 / 4 = 2, remainder 1. In C#, you get the same result using 9 % 4.
When dealing with division between two numbers, of which at least one is a real number, the result is a real number, not integer. Example: 5.0 / 2 = 2.5
Unlike integers, you are allowed to divide real numbers by 0.0, and the result is positive infinity, negative infinity or a special kind of result named NaN, which means “not a number”, and represents an invalid value.
The concepts explained in this lesson are also shown visually as part of the following video:
EXERCISES
1. Write an expression that checks whether an integer is odd or even.
Solution
Guidelines: Take the remainder of dividing the number by 2 and check if it is 0 or 1 (respectively the number is odd or even). Use % operator to calculate the remainder of integer division.
Tags: arithmetical operators, operators