CSC126 Tutorial 4
CSC126 Tutorial 4
Objectives:
Arithmetic Operators
• C++ operators:
o ‘ + ’ = addition
o ‘ - ’ = subtraction
o ‘ * ’ = multiplication
o ‘ / ’ = division
o ‘ % ’ = remainder (mod operator)
• Order of precedence:
o Operations inside () are evaluated first
o *, /, and % are at the same level of precedence and are evaluated next
o + and - and have the same level of precedence and are evaluated last
o When operators are on the same level, performed from left to right
Multiple Operators
• Unary operators:
o are those that require only one operand
o For example: ++num;
• Binary operators:
o operator that operates on two operands
o For example: x * y;
Additional operators:
• C++ does not define operators for finding square roots, absolute values, or logarithms, or for
raising numbers to a power
• It provides predefined program units called functions that do these and other necessary
calculations.
• Example:
o √𝑥 = sqrt (x)
o √𝑎 − 𝑏 = sqrt (a-b)
o |x| = abs (x)
o |y| = fabs (y)
o |a*r| = fabs (a * r)
o xy = pow (x, y)
Task 1: Trace the output of following statements
int a = 0, b = 1, c = 2;
Task 2: Given the declarations below, find the results of each expression.
a) a+b*c
b) a-b-c
c) a/b
d) b/a
e) a-b/c
f) w/y
g) y/w
h) a+w/b
i) a%b/y
j) b%a
Task 3: Given the declarations below, find the results of each expression
double x = 14.5;
double y = 11.0;
double b, z;
int n = 9;
int m = 5;
int i, j, k;
a) z = x - n / m;
b) b=x*y+m/n*2;
c) i = int (x + 0.5) ;
d) j=x*m-n%m;
e) k = m / -n ;
Task 4: Write a C++ assignment statement for each of the following mathematic expression.
a. 𝑍 = 𝑋𝑌 + 2𝑀!
"
b. 𝑎 = .|𝑏 + 𝑐| + #
c. 𝐾 = (𝐿 + 𝑀$ + 5𝑅)/3𝐹𝐶 #
#%&'
d. 𝑎 = % ! &'
#
e. 𝑏 = ;𝑥 −
$'
f. 𝑎 = 2𝑥 ($'&))
g. 𝑏 = 5.(𝑥 + 𝑦)