Lecture 05
Lecture 05
Operators in C
Sachintha Pitigala
© 2023
Expressions in C
● Most of the C statements are expressions.
● Example:
2
Assignment Operator (=)
● In C, equal sign (=) is called as the assignment operator.
int x, y, z;
x = y = z = 12;
float n = 4.5;
4
Arithmetic Operators
● Arithmetic operators are used to perform calculations in
C.
● Example statements:
○ What does each one mean?
■ cost = price + tax;
■ owed = total - discount;
■ area = l * w;
■ one_eighth = 1 / 8;
■ r = 5 % 2;
■ x = -y;
6
The Modulus Operator
● The modulus operator (%) returns the remainder rather
than the result of division.
● Examples:
○ 9 % 2 would result in 1.
○ 10 % 2 would result in 0.
○ 20 % 6 would result in 2.
7
The Negation Operator
● The negation operator used to flip the sign of a number.
● It is a unary operator.
● Examples:
int x = 10;
printf (“%d\n” , -x);
output:
-10 8
Incrementing and Decrementing Operators
● Adding one to a variable is called incrementing.
9
Incrementing and Decrementing Operators
● Variation if increment and decrement (Post
increment/decrement and Pre increment/decrement)
k = j++;
○ In the case of the statement above, k is assigned the value
of the variable j before j is incremented.
k = ++j;
○ right to left
6/2 * 1 + 2 = 1
● using parentheses
= 6 / (2 * 1) + 2
= (6 / 2) + 2
=3+2
=5 12
Order of Operators (Operator Precedence)
•The following table operators are listed top to bottom, in
descending precedence.
2 (+), (-), ++, - - Unary plus or minus, prefix increment or Right to left
decrement
● in this case the multiplication would happen first, but you might
want the addition first
● Example:
total = totalSale + TAXRATE * totalSale
becomes
total = (totalSale + (TAXRATE * totalSale))
15
Operator Precedence - Examples
16