Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Chapter 2

C++ Basics

Part 2
Operators
 Assignment operators (=)
 Arithmetic operators
 (+, -, *, /, %)
 Ex: % Modulus
 int Y = 13%5;
 int Z = 1%5;
 Relational operators
(less than, greater than, less than
or equal, greater than or equal,
equal, not equal) x y x&&y x||y
(<, >, <=, >=, ==, !=) x !x 0 0 0 0

0 1 0 1 0 1
 Logical operators are
(not, and, or) 1 0 1 0 0 1
( !, &&, ||)
1 1 1 1
In Class Assignment
What is the value of the following expressions: x=6, y=7, z=10,
a=True, b=False, c= True
1. x==y 7. z%y 13. a&&b
2. x+2 >y 8. z%x 14. !b
3. y*2 <z 9. y%x 15. !b&&a
4. z>=y 10. y%x 16. a||b
5. z-5 <= x 11. x%z 17. !c ||b
6. y>=z 12. x%y
Compound Operators
 Ex: use x=2.0,y=5.0 to get
 x+= y  x=x+y=7

 x-=y  x= x-y=-3
Operator Example Equivalent
Sign
 x*=y  x=x*y=10
+= G+=B G=G+B
-= G-=B G=G-B  x/=y  x=x/y=0.4
*= G*=B G=G*B
/= G/=B G=G/B  x%=y  x=x%y=2
%= G%=B G=G%B
 y%=x  y=y%x=1
Sample Program By definition "Stdafx.h" is a precompiled
1. #include "stdafx.h" header.
2. #include "iostream" Precompiled the word implies that this header
file is precompiled (once compiled no need to
3. using namespace std;
compile it again).
Precompiled Header stdafx.h is basically used
4. int main() { in Microsoft Visual Studio.
5. float x=2.0, y=5.0;
6. x+=y;
7. cout <<"x+=y " << x << endl;
8. x=2.0;
9. x-=y; X+=y 7.0
10. cout <<"x-=y " << x << endl;
11. x=2.0; X-=y -3.0
12. x*=y;
13. cout <<"x*=y " << x << endl;
14. x=2.0; X*=y 10.0
15. x/=y;
16. cout <<"x/=y " << x << endl;
17. x=2.0; X/=y 0.4
18. return 0; }
Increment & Decrement Operators
 Increment Operator
 ++ operator is used to increment variable as follows
 ++a
 Ex.
int a=10;
++a; a=11
 Decrement Operator
 -- operator is used to increment variable as follows
 --a
 Ex.
 int b=10;
 --b; b=9
Precedence of Operations
Precedence of Operations
W= x*y*z +a/b-c*d
1. x*y*z
2. a/b
3. c*d
4. +
5. -
This is similar to expression
W= (x*y*z) + (a/b) – (c*d)
Exercise
 What is the output of the program
1. #include "stdafx.h"
2. #include <iostream>
3. using namespace std;

4. int main( ) {
5. int a=3;
6. int b=4;
7. int y=-10;
8.

9. cout <<" a%b= " << a%b << endl;


10. cout <<" a/y= " << a/y << endl;
11. cout <<" a%y= " << a%y << endl; a%b=3
a/y=0
12. return 0; } a%y=3
Exercise
 Show in steps the result of the following expression, if a=5, b=10,
c=15 and flag = false
(a != 7) && flag || (a+c) <= 20
(a != 7) && flag || (a+c) <= 20

(5 != 7) && flag || (5+15) <= 20

true && false

false || true

true
Exercise
 Show in steps the result of the following
expression, if a=5, b=10, c=15 and flag = false
1. !(b <= 12) && (a%2 == 0)
2. !( (a > 5) || c < (a + b) )
3. (c > a) && !(b >= c)

You might also like