Lecture - 03-Expressions, Operators & Assignments
Lecture - 03-Expressions, Operators & Assignments
x + 2 * 5 + 6 / y
2
ARITHMETIC OPERATORS
Most familiar operators are drawn from mathematics
4
ORDER OF PRECEDENCE
Example
3*7-6+2*5/4+6 means
(3 * 7) - 6 + ( ( 2 * 5) / 4 ) + 6
= 21 - 6 + (10 / 4) + 6 (Evaluate *)
= 21 6 + 2 + 6 (Evaluate /)
= 15 + 2 + 6 (Evaluate -)
= 17 + 6 (Evaluate first +)
= 23 (Evaluate +)
5
COMPOUND ASSIGNMENT
x *= y (x = x * y)
x /= y (x = x / y)
x %= y (x = x % y) int main ()
x += y (x = x + y) {
x -= y (x = x - y) int x=5;
x /= y + 3 (x = x / (y+3)) int y=4;
Compound
x*=y;
assignment
cout<<x<<endl;
return 0;
}
6
INCREMENT AND DECREMENT OPERATORS
Increment operator - increment the value of a variable by 1
Decrement operator- decrement the value of a variable by 1.
7
OPERATORS
1. Assignment Operations
2. Arithmetic Operations
3. Relational Operations
4. Logical Operations
8
ASSIGNMENT OPERATORS
Example:
a = 5;
9
ARITHMETIC OPERATORS
10
RELATIONAL OPERATORS
11
LOGICAL OPERATOR
And
true and true true
true and false false
In c++ : &&
Or
true or false true
false or false false
In c++ ||
Not
not true false
In c++ !
12
LOGICAL OPERATOR - USAGE
int a = 4, b = 0;
a && b
a || b
!a
!b
(a+b)
(a-4)
13
LOGICAL OPERATORS TRUTH TABLE
14
EXPRESSIONS
2+5 Expression
Operator
15
C++ EXPRESSION FORMAT
16
PRIMARY EXPRESSIONS
17
BINARY EXPRESSIONS
18
BINARY EXPRESSION
-- MULTIPLICATIVE EXPRESSIONS
10 * 12
20 / 4
5 % 2 ???
Modulus Operator (%)
5 % 2 1
5 % 3 2
6 % 3 0
19
BINARY EXPRESSION
-- ADDITIVE EXPRESSIONS
Additive expression
3 + 5, 4 6
20
ASSIGNMENT EXPRESSIONS
The assignment expression has a value and a result.
Value: the value of the expression on the right of the assignment operator (=).
Result: the result copies the expression value to the left of the assignment operator.
21
SIMPLE ASSIGNMENT
Examples
22
COMPOUND ASSIGNMENT
Examples
23
SAMPLE CODE FOR ASSIGNMENT EXPRESSION
24
POSTFIX EXPRESSIONS
Remember!
(a++) is (a = a + 1)
(a ) is (a = a 1)
25
UNARY EXPRESSIONS
Remember!
(++a) is (a = a + 1)
( a) is (a = a 1)
26
OPERATOR PRECEDENCE EXAMPLES
2+3*4
( 2 + ( 3 * 4) )
-b++
( -( b++ ) )
27
OPERATOR ASSOCIATIVITY
Determine the
evaluation order
of the operators having
the same precedence
28
OPERATOR ASSOCIATIVITY EXAMPLES
Left associativity
Right associativity
29
30
STATEMENTS
A block of instructions
Types of statements
31
EXPRESSION STATEMENTS
Examples
a = 2;
a = b = 3;
a = 4 + 5;
a = b + (45 / c) + 22;
a++;
33
SAMPLE PROGRAMS
34
Sample Programs
35
SAMPLE PROGRAMS
36
SAMPLE PROGRAMS
37
38
39
40
41
UNARY OPERATORS
UNARY
SUBTRACTION ( )
MULTIPLICATION ( * )
int num_1;
int num_2;
int num_3;
int answer;
Mathematical formula:
________
- b + b2 - 4 a c
----------------------
2a
C# formula:
(- b + sqrt ( b * b - 4.0 * a * c) ) / ( 2.0 * a )
CLASS ACTIVITY
FOLLOWING TABLE SHOWS ALL THE ARITHMETIC OPERATORS SUPPORTED BY C#. ASSUME
VARIABLE A HOLDS 10 AND VARIABLE B HOLDS 20, THEN:
30
-10
200
2