Fundamentals of Computer Programming: Operators in C++
Fundamentals of Computer Programming: Operators in C++
Fundamentals of Computer Programming: Operators in C++
Lecture 6
Operators in C++
Course Instructor:
Aisha Shabbir NUST
Institute of Geographical Institute Systems
Information of Civil
Engineering (NICE)
Road Map for Today
• RECAP
• Operators
o Stream Operators
o Decision Making – Equality and Relational
Operators
o Assignment/ Combined Operators
o Unary Operators
o Logical Operators
o Conditional operator
Operators in C++
Binary
operators
?
Unary Operators
return 0;
}
Institute of Geographical Information
Systems
Postincrement - Example
#include <iostream>
using namespace std;
Output
int main() 1
{ 2
int var = 1; 3
4
cout << var++ << endl; 5
cout << var++ << endl;
cout << var++ << endl;
cout << var++ << endl;
cout << var++ << endl;
return 0;
}
return 0;
}
?
{ 3
int var = 4; 2
1
cout << var-- << endl;
cout << var-- << endl;
cout << var-- << endl;
cout << var-- << endl;
return 0;
}
?
{ 22
int a = 21; 22
int c ; 24
c = ++a;
cout << ++c << "\n";
cout << a<< "\n";
cout << a++<< "\n";
Cout<<++a<< "\n";
return 0;
}
?
{
int x = 5, y = 5;
cout << ++x << --y << endl;
return 0;
}
+ + variable variable --
Incorrect Incorrect
Common Mistakes – Syntax Error
Attempting to use the increment or decrement
operator on an expression other than a variable
name is a syntax error.
++(x+2)
Incorrect
Caution
Be VERY CAREFUL using these operators.
C++ allows these operators to be used in the middle
of a larger expression.
Truth table
&& – Logical AND – Example
Truth table
|| – Logical OR – Example
…if age is 15, 31, or 45 then give 10% discount…
In case of an IF condition
IF age == 15 then
give discount
ENDIF
IF age == 31 then
give discount
ENDIF
|| – Logical OR – Example
…if age is 15, 31, or 45 then give 10% discount…
In case of an IF condition
IF age == 45 then
give discount
ENDIF
|| – Logical OR – Example
…if age is 15, 31, or 45 then give 10% discount…
! – Logical NOT (logical negation)
Used to reverse a condition’s meaning
!(condition)
Truth table
! – Logical NOT – Example
…if age is NOT more than 30 then give 5% discount…
(condition)?expression1:expression2;
tp u t
Ou
int main ()
value of x: 40
{
?
// variable declaration
int x, y = 10;
return 0;
}
y = ax + bx + c 2
1. [5 marks] Convert the above given algebraic
expression to C++ expression and also number
the precedence order in which the operators will
be evaluated.