4 Lecture FoP Operators
4 Lecture FoP Operators
Operators
Dr Ayesha Zeb
Email: [email protected]
Lecture Contents
• Operators:
– Arithmetic operators
– Logical operators
– Relational operators
Operators
“Operators are words or symbols that cause a program to
do something to variables.”
• Binary – use 2 variables
• Unary – use 1 variable
Operators
Operators are words or symbols that cause a program to do something to
variables.
OPERATOR TYPES:
Type Operators Usage Binary/Unary
Arithmetic ‘+’ ‘-’ ‘*’ ‘/’ a+b a-b a*b a/b a%b Binary
‘%’
Arithmetic ‘+=’ ‘-=’ ‘*=’ a+=b is the same as Binary
assignment ‘/=’ ‘%=’ a=a+b
a-=b a*=b a/=b a%=b
Increment ‘++’ ‘- -’ a++ is the same as Unary
and a=a+1
decrement a-- is the same as a=a-1
Relational ‘<’ ‘>’ ‘<=’ ‘>=’ Binary
‘==’ ‘!=’
Logical ‘&&’ ‘||’ ‘!’ Binary/Unary
Bitwise ‘&’ ‘|’ ‘^’ ‘~’ Binary/Unary
‘<<’ ‘>>’
Assignment Operator
• Syntax:
– variable = expression
– (LHS) (RHS)
• Read as place the value of expression (RHS) in variable
on LHS
Arithmetic ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘%=’ a+=b is the same as a=a+b
assignment a-=b a*=b a/=b a%=b
Assignment and increment
a:
// changing the value of a variable
7
int a = 7; // a variable of type int called a
// initialized to the integer value 7
a = 9; // assignment: now change a's value to 9 9
• In algebra
𝑎+𝑏+𝑐+𝑑+𝑒
𝑚=
5
• In c++
𝑚 = (𝑎 + 𝑏 + 𝑐 + 𝑑 + 𝑒)/5
𝑦 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
2nd Degree Polynomial
𝑦 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
Evaluate
• 4 + 3/2
• ++
• --
• Increase/decrease by 1
• Postfix
– Fixed after the variable (a++)
• Prefix
– Fixed before the variable (++a)
Increment/Decrement Operators
➢ Prefix:
– inc or dec occurs first and then the new variable value is used in
the rest of the expression.
➢ Postfix:
– Variable is used in the expression first and inc or dec occurs
afterwards.
int i=1,j=2,k=3
ans=i++ + j - --k;
Int i=1,j=2,k=4
Ans=++i + j – k--;
x is less than y or y is
or || (x<y) || (y<z)
less than z
= *= /= %= += -= assignment
Precedence of Operators
• a += b || c-- + d++ * a % e / f
• Consider all variables to be OPERATORS
equal to 2 and calculate the
++ --
answer
* / %
• a=? + -
<< >>
a b c d e f < > <= >=
2 2 2 2 2 2 == !=
&& ||
= *= /= %=
+= -=
• a += b || c-- + d++ * a % e / f
• Consider all variables to be equal to 2 and calculate the
answer
• a=3
Summary