0% found this document useful (0 votes)
25 views43 pages

4 Lecture FoP Operators

Operators in C++

Uploaded by

bilalasim1020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views43 pages

4 Lecture FoP Operators

Operators in C++

Uploaded by

bilalasim1020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

CS-114 Fundamentals of Programming

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

a = a+a; // assignment: now double a's value 18

a += 2; // increment a's value by 2 20

++a; // increment a's value (by 1) 21


Operator Precedence
Polynomials in C++

• In algebra
𝑎+𝑏+𝑐+𝑑+𝑒
𝑚=
5
• In c++
𝑚 = (𝑎 + 𝑏 + 𝑐 + 𝑑 + 𝑒)/5

• What happens if I don’t put the parenthesis ()?


The Modulus Operator

• % is known as the Modulus Operator or the Remainder


Operator.
• It calculates the remainder of two variables
• It can only be used with two ints..
Evaluate

In what order will the expression be evaluated?


Evaluate

In what order will the expression be evaluated?


2nd Degree Polynomial

𝑦 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
2nd Degree Polynomial

𝑦 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
Evaluate

• 4 + 3/2

• What are your data types?


Casting

• C++ is a strongly typed language


• If 3 and 2 are both integers the result would be an
integer
• Solution: CASTING
– Casting – converting from one type to another
• Write 4.0 + 3.0 / 2.0 [explicitly use doubles]
• Implicit cast:
– 4 + 3.0 /2 (everything else is converted into a double)
• Explicit cast:
– 4 + (double) 3 / (double) 2
Type Conversion
// shows mixed expressions
#include <iostream>
using namespace std;
int main(){
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
/* the lower-type variable is converted to the type of the
higher-type variable. Thus the int value of count is
converted to type float and stored in a temporary
variable before being multiplied by the float variable
avgWeight. The result (still of type float) is then
converted to double so that it can be assigned to the
double variable totalWeight *********/
cout << "totalWeight=" << totalWeight << endl;
system("PAUSE");
return 0;
}
Type Conversion
Type Cast

• In C++ the term applies to data conversions specified by


the programmer, as opposed to the automatic data
conversions.
• Sometimes a programmer needs to convert a value from
one type to another in a situation where the compiler will
not do it automatically or without complaining.
• Here’s a statement that uses a C++ cast to change a
variable of type int into a variable of type char:
aCharVar = static_cast<char>(anIntVar);
• Here the variable to be cast (anIntVar) is placed in
parentheses and the type it’s to be changed to (char) is
placed in angle brackets.
Type Conversion
// cast.cpp
// tests signed and unsigned integers
#include <iostream>
using namespace std;
int main()
{
int intVar = 1500000000; //1,500,000,000
intVar = (intVar * 10) / 10; //result too large
cout << "intVar = " << intVar << endl; //wrong answer
intVar = 1500000000; //cast to double
intVar = (static_cast<double>(intVar) * 10) / 10;
cout << "intVar = " << intVar << endl; //right answer
system("PAUSE"); return 0;
}
Increment/Decrement Operators

• ++
• --
• Increase/decrease by 1
• Postfix
– Fixed after the variable (a++)
• Prefix
– Fixed before the variable (++a)
Increment/Decrement Operators

• num = num +1; is equivalent to num++;


• num = num -1; is equivalent to num- -;
Increment/Decrement Operators
Increment/Decrement Operators

• The choice of using prefix or postfix does not matter if you


are inc / dec single variable on lines by themselves.
• When you combine these operators with other operations
in a single expression, you must be aware of the
difference.
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.

• Precedence of postfix is lowest in the priority table and


prefix operator has almost the highest precedence.
Postfix/Prefix Increment – An Example
Postfix/Prefix Increment – An Example

int i=1,j=2,k=3
ans=i++ + j - --k;

What will be the ans?

• What will be the value of i, j and k?


Postfix/Prefix Increment – An Example

Int i=1,j=2,k=4
Ans=++i + j – k--;

What will be the ans ?


Value of i, j and k?
Relational and Equality Operators
Standard algebraic C++ equality Sample C++ Meaning of C++
equality or relational or relational condition condition
operator operator
Relational operators
> > x>y x is greater than y

< < x<y x is less than y


 >= x >= y x is greater than or
equal to y
 <= x <= y x is less than or
equal to y
Equality operators
= == x == y x is equal to y
 != x != y x is not equal to y

(Deitel and Deitel (5th Ed), fig 2.12)


Logical Operators

Standard logical C++ logical Sample C++ Meaning of C++


operator operator condition condition

x is less than y and y


and && (x<y) && (y<z)
is less than z

x is less than y or y is
or || (x<y) || (y<z)
less than z

not ! !(x<y) x is not less than y


• Convert the following condition into c++ code
• a is less than 20 and b is greater than 100
• a is not equal to b
• Is there any difference between = and == in
c++ , if so explain
Logical Operators

• Logical operators are carried out on statements, e.g.


statement1 && statement 2, etc.

Var1 Var2 Result Var1 Var2 Result


False False False False False False Var1 Result
False True False False True True False True
True False False True False True True False
True True True True True True
NOT
AND OR
Bitwise Operators
• Bitwise operators are carried out on bits ,e.g. bit1 & bit2, etc.
Operators Name Operation
& Bitwise inclusive AND Result = 1 iff both bits at 1

| Bitwise inclusive OR Result = 1 if either bit is 1

^ Bitwise exclusive OR Result = 1 iff only one bit is 1


Shifts the bits of the first operand left by the
<< Left shift number of bits specified by the second
operand; fill from right with 0 bits. .
Shifts the bits of the first operand right by the
number of bits specified by the second
>> Right shift
operand; the method of filling from the left is
machine dependent.
Result = 1 if bit=0
~ Bitwise complement
Result = 0 if bit=1

(Deitel and Deitel (5th Ed), fig 22.5)


Left and Right Shift

• E.g. 8<<1 = 16 (1000<1 = 0001 0000)


• E.g. 8>>1= 4 (1000>1 = 0100)
Left and Right Shift

• Left shift = multiply by 2


• Right shift = divide by 2
Task

• Write Answers of Following


o 1&&2 =
o 1&2 =
o 1||2 =
o 1| 2 =
o 1&&0 =
o 1&0 =
o 1| |0 =
o 1| 0 =
o 8>>2 =
o 4<<2 =
Task

• Write Answers of Following


o 1&&2 = 1
o 1&2 = 0
o 1||2 = 1
o 1| 2 = 3
o 1&&0 = 0
o 1&0 = 0
o 1| |0 = 1
o 1| 0 = 1
o 8>>2 = 2
o 4<<2 = 16
Precedence of Operators
OPERATORS TYPE
++ -- unary
* / % multiplicative
+ - additive
<< >> shift
< > <= >= relational
== != equality
&& || logical

= *= /= %= += -= 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 == !=
&& ||
= *= /= %=
+= -=

EC100 - Algorithms & Computing -Lec Fatma Faruq-


DMTS - CEME, NUST
Precedence of Operators

• a += b|| c--+d++*a%e/f • a+=2||2--+2++*2%2/2


• a=2 • a+=2||2--+4%2/2
• b=2 • a+=2||2--+0/2
• c=2 • a+=2||2--+0
• d=2 • a+=2||2
• e=2 • a+=1
• f=2 • a=3
• c=1
• d=3
Precedence of Operators

• a += b || c-- + d++ * a % e / f
• Consider all variables to be equal to 2 and calculate the
answer
• a=3
Summary

• By the end of this lecture, you should know


– Arithmetic Operators and their precedence
Acknowledgement/References
• Slides contents taken from Ma’am Fatima Faruq

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like