C++
Input & Operators
Lecture- 2
Raghav Garg
Today’s checklist
1) Taking Input
2) Operators
3) Typecasting
4) Hierarchy of operators
5) Char and ASCII
Taking input // Let us take a simple example
int x;
cout<<”Enter a number\n”;
cin<>x; </ user will give ‘x’ a value.
int y = x*x;
cout<<square of number that you gave is”<<y;
Taking input // SUM of 2 given numbers
int x;
cout<<Enter first number\n”;
cin<>x; </ user will give ‘x’ a value.
int y;
cout<<Enter second number\n”;
cin<>y; </ user will give ‘y’ a value.
int sum = x+y;
cout<<”sum of the numbers that you gave is”<<sum;
Taking Input
Predict the output :
main(){
int p,q;
cout<<"Enter values of p and q";
cin<>p<>q;
cout<<”p =“<<p<<” q ="<<q;
}
Types of Operators
● Arithmetic Operators(already done in last lecture)
● Relational Operators
● Logical Operators (will be covered in IF-ELSE)
● Assignment Operators
● Bitwise Operators (will be covered in bit
Manipulation)
C++ Relational Operators
== Is Equals to
! = Not Equals to
> Greater Than
C++ Relational Operators
< Less than
<=Greater than or equals to
<=lesser than or equal to
C++ Assignment Operators
+=
-=
/=
%=
Ques: What is the result of the following code fragment?
bool p = false;
bool q = false;
bool r = true;
cout<<(p <= q <= r);
char data type
char ch = ‘a’;
ASCII values
char ch = ‘a’;
Typecasting
Ques : Take integer as input and print half of the
number.
Ques : Take float input and print the fractional part
of the real number.
Hierarchy of operators
int i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8 ;
cout<<i;
Hierarchy of operators
Ques: What is the result of the following code fragment?
int main()
{
int num1;
int p = 5, q = 10;
p += q -= p;
cout<<p<<" "<<q<<endl;
return 0;
}
Try This!
Predict the output :
int main(){
int i = 2, j = 3, k, l;
float a, b;
k = i / j * j ;
l = j / i * i;
a = i / j * j ;
b = j / i * i;
cout<<k<<” “<<l<<” ”<<a<<” “<<b;
}
MCQ Time !
MCQ 1
Which of the following is NOT a character constant
(1) ‘Thank You’
(2) ‘Enter values of P, N, R’
(3) ‘23.56E-03’
(4) All the above
MCQ 2
In b = 6.6 / a + 2 * n ; which operation will be performed first?
(1) 6.6 / a
(2) a + 2
(3) 2 * n
(4) Depends upon compiler
MCQ 3
The expression, a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ; evaluates to
(1) 8.28
(2) 6.28
(3) 3.14
(4) 0
MCQ 4
The expression x = 4 + 2 % - 8 evaluates to
(1) -6
(2) 6
(3) 4
(4) None of the above
THANK YOU