Similarly to find the remainder the operator is used For example to find the

# Similarly to find the remainder the operator is used

This preview shows page 2 - 4 out of 7 pages.

Similarly, to find the remainder the operator % is used. For example, to find the remainder when 7 is divided by 3 we write 7 % 3 which gives an answer of 1 . Example: Let x, y, z are integer variables and c is a float variable. Also let x = 9, y = 11, z = 16. Then c = x / 5 + y / 2 + z / 5 will give the answer as 9 (1+5+3) and not 10.5 (1.8+5.5+3.2). But if we write c = (float) x / (float) 5 + (float) y / (float) 2 + (float) z / (float) 5 OR c = (float) x / 5 + y / (float) 2 + z / (float) 5 we will get the correct answer of 10.5 and it does not change the x, y, z to be of float type . They will remain as integers only. Consider the case where z is of type float . Then there is no need for placing (float) before z and before 5 because if any one of the operand is float the answer will also be of float type. Consider another example , int i=7, x=11 , y=13 ; float z, a , b ; a = x / 3 + y / 2.5 – z / 3 ; b = i / 2.5 + x / 4 + y / 1.2 ; can be written to get the correct answer as: a = (float) x / 3 + y / 2.5 – z / 3 ; b = i / 2.5 + (float) x / 4 + y / 1.2 ; Note that there is no need of (float) cast for y / 2.5 and i / 2.5 because if any one of the operands is float the other is automatically converted to float but only during the operation and not always . Rules for Evaluation of Arithmetic expressions: 1) All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expressions evaluated first. Page 2 of 7
2) The operator precedence rule: Operators in the same sub expression are evaluated in the following order: Unary + and – are evaluated first. *, /, % are evaluated next . binary operator + and are evaluated last . 3) The associativity rule: Unary operators in the same sub expression and at the same precedence level (such as + and -) are evaluated right to left (right associativity).

#### You've reached the end of your free preview.

Want to read all 7 pages?

• Spring '10
• zaman
• Algebra, Expression