CSC126 Tutorial - Lab 4
CSC126 Tutorial - Lab 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. 𝑎𝑎 = �|𝑏𝑏 + 𝑐𝑐| +
2
2𝑥𝑥−𝑦𝑦
d. 𝑎𝑎 =
𝑥𝑥 3 −𝑦𝑦
2
e. 𝑏𝑏 = �𝑥𝑥 −
3𝑦𝑦
f. 𝑎𝑎 = 2𝑥𝑥 (3𝑦𝑦−1)
g. 𝑏𝑏 = 5�(𝑥𝑥 + 𝑦𝑦)
Task 5: Write a C++ assignment statement for each of the following mathematic expression.
|𝑎𝑎+𝑏𝑏2 |
a) 𝑉𝑉 =
𝑎𝑎−𝑐𝑐
2𝑎𝑎
b) 𝑊𝑊 = + √𝑐𝑐
𝑏𝑏
𝑎𝑎+𝑏𝑏+𝜋𝜋
c) 𝑋𝑋 =
√𝑑𝑑 3
1
d) Y = 7ab + 2 𝑐𝑐𝑑𝑑4
e) 𝑍𝑍 = √𝑎𝑎𝑏𝑏 3 + 𝑎𝑎𝑏𝑏 2