Operators and Conditional
Operators and Conditional
CSC-112
Lecture 3
Operators
Operators
• “Operators are words or symbols that cause a program
to do something to variables.”
OPERATOR TYPES:
Type Operators Usage
Arithmetic ‘+’ ‘-’ ‘*’ ‘/’ ‘%’ a+b a-b a*b a/b a%b
Arithmetic ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘%=’ a+=b is the same as a=a+b
assignment a-=b a*=b a/=b a%=b
Increment and ‘++’ ‘- -’ a++ is the same as a=a+1
decrement a-- is the same as a=a-1
Relational ‘<’ ‘>’ ‘<=’ ‘>=’ ‘==’ ‘!=’
Logical ‘&&’ ‘||’
Common Operators
• Common Mathematical Operators:
- Common mathematical operators are available
in C++ for manipulating values e.g. addition(+),
subtraction(-), multiplication(*), division(/),
and modulus (%).
•C, C++ has many other operators also which
we will study in due course.
Arithmetic Expression Evaluation
6+2*3/6
• Three operators are in this expression.
• However, * and / both have the same precedence and + has
lower precedence then these two.
• * and / will be evaluated first but both have the same
precedence level.
• Therefore, operator associatively will be used here to
determine the first to get evaluated i.e. left to right.
• The left most sub expression will be evaluated followed by
the next right one and so on.
– 3%2 =1
– 5%2=1
– 6%3=0
– 8%5=3
Arithmetic Operator Precedence and
associativity
Polynomials in C++
• In algebra
𝑎+𝑏+𝑐+𝑑+𝑒
𝑚=
5
• In c++
𝑚 = (𝑎 + 𝑏 + 𝑐 + 𝑑 + 𝑒)/5
𝑦= 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
2nd Degree Polynomial
𝑦= 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
Arithmetic Assignment Operators
Prefix
++a;
--a;
Postfix
a++;
a--;
Precedence of Operators
OPERATORS TYPE
++ -- unary
* / % multiplicative
+ - additive
< > <= >= relational
== != equality
&& || logical
= *= /= %= += assignment
-=
Home Task
Precedence of Operators
• a += b-- + ++d * c % e / f
a condition.
– if condition is true -> action is done
– if condition is false -> action is not done
The if statement
Any statement that
results in True or False
if (condition)
T
{ statement1; F
statement 2;
….
statement n;
}
The if statement
• Develop a system that tells the user that he is
over-speeding if his speed crosses120km/hr.
• Pseudocode
IF speed is greater than 120km/hr
THEN print “over-speeding”
The if statement
if (speed>120)
{cout<<"over speeding";
cout << "reduce speed now";
} T
… F
…
…
If - else
• Pseudocode
• IF number is greater than or equal to 0,
THEN print “positive”
• ELSE print “negative”
If - else
if (number>=0)
cout<<"number is positive";
else
cout<<"number is negative";
If - else
• TRY ME! : for even numbers add half the
number to y. For odd numbers, subtract half.
if (x%2==0)
y += x/2;
else
y -= x/2;
Some notes
• If there is only one statement following the if,
then the curly braces are optional.
• If there are multiple statements, the braces
are necessary.
• Same is true for the statements following the
else.
Some notes
– E.g.
if (a<b)
a=b+1;
b = 10;
cout<<"print A"<<a;