Lecture 2 - Expressions
Lecture 2 - Expressions
E = mc2
● An expression is a combination of variables and operators that
compute a value.
● m and c are both variables that may store any value. They are places
within operators.
2
Operators
3
Operators in C
● Operators are special symbols that tell the computer to perform special
mathematical, logical or conditional operations.
● Some well known operators are: +, -, *, /
Operators in C
● Arithmetic operators
● Relational operators
We will learn about these in other lectures
● Logical operators
● Assignment operators
● Increment & decrement operators
4
Arithmetic operators
5
Arithmetic operators
As the name suggests, these operators are used for mathematical operations in
between variables.
Unary operators
● + or -
● Used to denote negative and positive numbers
Binary operators
● + (addition)
● - (subtraction)
● * (Multiplication)
● / (Division)
● % (Remainder)
6
Arithmetic operators
average = sum / count;
E = m * (c * c);
7
Arithmetic operators
What will be stored in rating
int rating, power = 10; // Declared 2 variables
rating = -power;
8
Pop Quiz
9
Arithmetic operators
● 10 + 10.5f = ?
● 10 % 3 = ?
● 1 / 2 = ?
● 1.0f / 2.0f = ?
10
Arithmetic operators
● 10 + 10.5f = 10.5 → This is a float
● 1 / 2 = 0 → The output should have been 0.5 but as both are int, output
gets truncated to 0
● 1.0f / 2.0f = 0.5 → This is the expected output. As both are float
11
Arithmetic operators
● What about this?
10.2f % 3.5f = ?
12
Operator precedence
13
Operator precedence ● Unary +, -
B → Brackets (...) ● *, /, %
● Binary +, -
O → Orders x2 + y2
D → Division /
● i+j*k → i+(j*k)
M → Multiplication * ● -i*-j → (-i)*(-j)
● -i+j/k → (-i)+(j/k)
A → Addition +
Unary operator has the highest
S → Subtraction -
precedence.
14
Operator precedence
What happens when there are operators with equal precedence?
● 5-7-12 → (5-7)-12
Left associative
● 10/2*5 → (10/2)*2
15
Pop Quiz
16
Operator precedence
● a + b * c / -d = ?
● 5 + 2 / 2 - 1 = ?
● -+-+-+i + +-j = ?
● -+x + y - x * y = ?
17
Assignment operators
18
Assignment Operators
Assignment operators assign some value to variables.
int i = 3, j;
j = 2 * i;
i = j = k = 0;
i = (j = (k = 0));
19
Assignment Operators
Be careful about type conversion in chained assignment
int i;
float f;
f = i = 33.5f;
20
Compound assignment
21
Compound assignment
Compound assignments use old value of a variable to compute new value
int x = 5;
x += 2; // x is now 7
22
Compound assignment
24
Increment & decrement operators
26
Pop Quiz
27
Increment & decrement operators
30
Reading Tasks
● C Programming - A Modern Approach | Chapter 4
31
Thank You
32