Lecture 06
Lecture 06
Lecture 6
EXPRESSIONS
13
Arithmetic Operators
• Addition, subtraction, multiplication work as expected for
both integer and floating point types
• Modulus is only defined for integers
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
(Integer vs. Double division)
% Modulus (remainder) 10 % 3 =
[for integers only] 17 % 10 =
14
Precedence
• Order of operations/
evaluation of an expression
• Top Priority = highest
(done first)
• Notice operations with the
same level or precedence
usually are evaluated left to
right (explained at bottom)
• Evaluate:
– 2*-4-3+5%2;
• Tips:
– Use parenthesis to add clarity
– Add a space between literals January 2007 v2.2. Copyright °c 2007 Joseph H. Silverman
Permission is granted to make and distribute copies of this card pro-
( 2 * - 4) - 3 + ( 5 % 2) vided the copyright notice and this permission notice are preserved on
all copies.
Send comments and corrections to J.H. Silverman, Math. Dept., Brown
Univ., Providence, RI 02912 USA. [email protected]
15
Division
• Computers perform division differently based on the
type of values used as inputs
• Integer Division:
– When dividing two integral values, the result will also be
an integer (any remainder/fraction will be dropped)
– 10 / 4 = 2 52 / 10 = 5 6/7=0
• Floating-point (Double) & Mixed Division
– 10.0 / 4.0 = 2.5 52.0 / 10 = 5.2 6 / 7.0 = 0.8571
– Note: If one input is a double, the other will be promoted
temporarily to compute the result as a double
16
Exercise Review
• Evaluate the following:
25 / 3
20 - 12 / 4 * 2
3 - 15 % 7
18.0 / 4
28 - 5 / 2.0
Exercises from: D.S. Malik, C++ Programming, 5th Ed., Ch. 2, Q6.
17
Using 'cout'…
return 0;
}
SOLUTIONS
21
Exercise Review
• Evaluate the following:
– 25 / 3 = 8
– 20 - 12 / 4 * 2 = 14
– 3 - 15 % 7 = 2
– 18.0 / 4 = 2.5
– 28 - 5 / 2.0 = 25.5