C++ Operator
C++ Operator
1. <<
Stream output operator
2. >> Stream input operator
3. endl Line feed operator
4. setw Field width operator
5. Scope resolution operator
6. Pointer-to-member operator
7. ->*
Pointer-to-member operator
8. Pointer-to-member declarator
9 new Memory allocation operator
10. delete Memory release operator
[49]
chapter. Th
Ihe first four operators have already been explained in the previous operators
TOCUses on allC operators and scope resolution operator (::). Ihe
POINTERS.
hew anddelete are explained in chapter on
Chapter Objectives
able to :
On completion of this chapter, youwill be
OExplain the arithmetic, relational, logical, shorthand assignment,
incrementand de
conditional and bitwis operators.
OExplain the sizeof, comma and scöpe fèsolution operators.
O Evaluate the arithmetic and boolean expression.
O Advantages of shorthand assigament operators.
OList the precedence in C++ operators.
ÞÉxplain the concept of Automatic type conversion in C++.
O Explain the concept of casting of data.
0 Write the purpose of common mathematical function.
O Write the simple C++ programs.
TABLE,1
Arithmetic Operators Purpose Example
addition i * , i:j 7+5 = 12
subtracion. 7-5=2
or uhary miñus
imuitpliation 7*5=35
division 7/5 = 1
remainder after division 7%5=2
The unary minus (-) operator
multiplies
preceded by a minus sign changes its sign.its When
singleboth
operand by -1. Therefore,
the operands are integers
then the result produces an integer value (or real value). If one operand is ofthere
and another is integer type, then the result is always a real number. The moduloo
folo
operator %cannot be used on floating point data. The as
operator % operates
[50]
% 2
-9 % 2 -1
9 % (-2)
-9 % (-2) -1
3 *5 |2 + 6 *9 % 3 + 2 3- 3
15 54 6
7 0
13
10
[51]
2. 3*(5 +2*3)+ 25/(2 *3+2)
(2 3 +2)
3) + 25 /
3' (5+2
lol lol 6
11
8
5
33
36
int exl,ex2;
exl=3*5/2+6*9%3+2*3-3;
ex2=3*(5+2*3)+25/(2*3+2);
cout<<Value of Ist expression is "<Kexlk<";
cout<<Value of 2nd expression is "<<er2k<";
return(0);
Run
Value of lst expression is 10
Value of 2nd expression is 36
15.0
9.0
30.0
3.0
5
27.0
40.5
3 / 2 (4.5 2.3 1)
1.0
2.3
1,0
6.8
6.8
[53]
Example 3.5
Wite the program to find the value of following expressions :
1. J*K+A
2. K/J * (A +2.3 *1)
Where A =4.5,1 =l, J=2 and K=3
Program
#include <iostream.h>
main)
float exl,ex2,A;
int 1,J,K;
A=4.5;
=l;
J=2;
K=3;
exl=J*K+A;
ex2=K/J*(A+2.3*1);
cout<<Value of Ist expression is <<exl<<"
cout<<Value of 2nd expression is <<ex2<<";
return(0);
Run
Value of Ist expression is 10.5
Value of 2nd expression is 6.8
[54]
Example 3.6
Write a program that accepts as
equivalernt in degrees celsius andinput temperature
output the
in degrees Fahrenheit, converts it to its
Algorithm temperature in degrees celsius.
1. Input temperature in Fahrenluit
compute the celsius temperature C= (5/9)(-32)
3. Output C
4. STOP
Program
#include <iostream.h>
main() Start
int f;
Read f
float c;
cout<<"Enter the temperature in Fahrenheit: ;
cin>>f; G= 5.0/9.0* ((-32.0)
c=5.0/9.0*(f-32.0);
cout<<Equivalent celsius tempeYatureis "<<c;."
return(0);
Run Stop
Enter the temperature in Fahrenheit:35
Equivalent celsius temperature is 1.666667
Self Check-1
I. Distinguish between unary and binary operators.
. What do you mean by associativity of a operators?
3. Evaluate the following
(0) 4
expressions
*5+5/2-9 %2
(0) 12.0/3.0 + 5.5 * 2.0 - 3.0
[55]
statements equivalent?
4. Are the following two
() m= 8%33;
(ü) m=83%3;
Check-1
Answers /Hints toSelf
1. Unay operators take one operand and are associated from right to \et
from left to riaht
operations take twooperands and are associated
Associativity tells what happens where several different operators with
2. precedence level appear in the same expression. For example, +and - bot
associative. So in the expression 20 + 8 7
from the sum.
first 8 is added to 20 and then 7 is subtracted
3. (0) 21 () 12.0
4. Hint: No.
15 > 5 is true
42 < 20 is false
Precedence of relational operators is
1. < <=
2.
>=
higher precedence.
lower precedence.
[56]
34 Logical Operators
There are three logical operators. Logical operators are
shown in table 3:
TABLE3
&&
means logical AND
means logical OR
means logical NOT
Truth Table of logical operators is shown in table 4.
TABLE 4
TABLE5
Operators Precedence
I(highest)
&& 2
= 3
[57]
3.5 Shorthand Assignment Operators
Form of Assignment operator is
variable operator = expression;
The assignment statement
variable operator = expression;
is equivalent to
variable = variable operator (expression);
Example 3.8
a +=7is equivalent toa =a+7
Some of the commonly used shortand assignment operators are given in thas
table 6.
TABLE 6
I=I-7 I-=7
X=x*y x *=y
x=xly x/=y
x=*%y
In this case, the value of yand mwould be 8. Suppose,ifwe rewrite the above statement
as
(b) m= 7;
y= m++;
then the value of y would be 7 and m would be 8.
Example 3.10
Write the program to find the value of following expressions
(a) x*++y
(b) x *y ++
Where x= 10 and y = 15
Program
#include <iostream.h>
#include <iomanip.h>
main)
int x,y,exl,ex2;
x=10;
y=15;
exl=r*++y;
cout<<Value of Ist expression is <<exl<<endl;
x=10;
y=15;
ex2=r*y++;
cout<<Value of 2nd expression is "<<er2<<endl;
return (0);
Run
Valueof Istexpression is 160
Value of 2nd expression is l50
[59]
3.7 Conditional Operator
Aternary operator pair "?:" is available in C++ to construct conditional expression,
form
expressionl ? expression2 : expression3;
evaluated first. If it is true (nonzero), then the expression2 is evalua
expression1 is othewise expression3 is evaluated and
becomes the value of the expression
becomes the value of the expression.
Example 3.11
*=5;
y=;
m=(r>y) ?x:y; m.
is greater than the value of x, so condition is false. Hence
Since value of y
assigned the value of y (i.e. 9).
The statement
m= (r>y) ?x: y;
Start
Read x,y
True False
Is
X>y
Big = x Big = y
Write Blg
Stop
[60]
Program
#include <iostream.h>
#include
main()
<iomanip.h>
float xy,big:
cout<<"Enter the two numbers"<<endl;
cin>>>>y;
big=(x>y?x:y); number is
cout<<Larger
return(0); <<hig<<endl;
Run
Enter the two numbers
12 45.7
Larger number is 45.70
38 Bitwise Operators
Bitwise operators are used to manipulate the data at bit level. List of bitwise operators is
given in the table 7.
TABLE 7
Operator Meaning
bitwise AND
bitwise OR
bityise exclusive OR
One's complement
<< shift left
shift right
A |B A^B
B A&B
A
0
1 1
[61]
Example 3.13
as
Suppose Aand Bare defined
A= 10100101
B=01101100
then
A& B=00100100
AIBll10110I
A ^B =1i001001
inverts all ha
The complerüent operator (-) is an unary operaor. This opeYaor
9iven expression.
'Example 3.14
Suppöse Ais defined as
A=001ll0101
It's complement will be given by
-A=11001010
The left shift operator shifts the bit patterns a number of bits to the left. X <ans
places to left the bits in operand X. The blank spaces produced at the right, because
shifting are padded with O's.
Example 3.15
Suppose
= 01010101
X<«3 = 10101000
The right shift operator shifts the bit pattern_ a number of bits to the right. X>>mS
places to right the bits in operand X:The blañk tpacèa' producèd atithe left, becaus
shifting are padded with 0's.
Example 3.1¬
Suppose
X 01010101
X>>3 00001010
[62]
Example3.17
To understandthe bitwise operators, study the following program
Program
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
void main()
int q=8,b=15;
clrser();
cout<<a^b is "<<(a^b)<<endl;
cout<<a&b is <<la&b)<Kendl;
cout<<alb is <<(alb)<<endl;
cout<<a<<3 is k<a«<3)<Kendl;
cout<<a>>3 is <<(a>>3)<<endl;
cout<<»'a is <<UKKendl;
getch();
Run
a^b is 7
a&b is 8
alb is 15
a<<3 is 64
a>>3 is
is -9
Explanation :
all the operations.are carried out oni 16 bit binary
considered,
Since integers are being
numbers. Thus
0000 0000 000
a=8
0000
b215 zii0090- 0000 0111 (74
0000 0000 0000
a ^b 1000 (8)
0000 0000 0000
a&b 1111 (15
0000 0000
alb 0000 0000 (64,
0000 0100
a <<3 0000 (4)
0000 0000 0001
a >>3
0000 0111 (65527)
1111
m- = 1;
m--;
--m;
2. m = 10, n = 3
3. ++, --, - (unary minurs), !
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
void main()
clrscr);
cout<< "Number of bytes used : <kendl;
cout<< char = <<sizeof(char)<<endl;
cout<< int = <<sizeofint)<<endl;
cout<< "float = "<<sizeof(float)<<endl;
[64]
cout<< '"double =
getch); "<<sizeof(double)<<endl;
Run
1.
Number of bytes used :
char = 1
int = 2
float = 4
double = 8
Using above program, you can verify the size of all data types of your own computer :
10Comma Operator
C++ USes the comma operator in three ways.
The first use of comma operator is as a separator in the variable declaration. The comma
also enables you to put more than one expression on a single line. For example,
int x, y, z; l separator in the variable declaration
square= (n * n), Cube= (n * n * n);
Il enables you to put more than one expression on a single line
2. The second use of comma operator is to string together a number of expressions which
are performed in asequence from left to right. For example, the following statement
x=(m = 10, m + 5);
executes in the following order
(a) value 10 is assigned to variable m
(b) m is incremented by 5
(C) finally, the value 15 is assigned to the variable x.
3. Another use is to combine expressions in a for loop. For example
for (i = 0,j=10; i< =6, j>= 5; it+, j- -)
1or loop is explained in detail in the next chapter on control statements.
3.11 Scope
Suppose
Resolution Operator
there are two variables with the same name m. Assume that one has been declared
outside all
functions (global) and anotheris declaredlocally inside afunction. In Clanguage,
[65]
variable. We
access the variable mthen we always access the local
iftheweglobal canngt
variable inside the function. C++ introduces the new operator :: called ,
resolution operator to solve this problem. Syntax of this operator is
:: variable_ name
mallows us to
Now :: maccess the global value of variable m. Hence,value access the
value of m, whereas :: m allows us to access the global of m.
Example 3.19
Following program illustres the scope resolution operator.
#include <iostream.h>
#include <conio.h>
int m=30; llglobal variable
void main()
clrscr();
int m = 10;: IMocal variable
cout<<Local m=<<m<<n";
cout<<Global m = <<i:m<<n";
m= 50; lIre-initialise global variable
cout<<Local m = KKm<<n";
cout<<Global m = Ki:m<<M";
getch);
Run
Local mn = 10
Global n = 30
Local m = 10
Global m = 50
It is clear from this program that not only we can access a global variable and wrie
existing value, but we can also reinitialize it to another value.
[(66]
Example 3.20
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
int m = 50; llglobal variable
void main()
cout<<m<<setw(5)<<::m<<endl;
getch();
Run
10 50 I/first cout
20 50 Il second cout
10 50 Il third cout
[67]
TABLE 9
Precedence Operators
AsLeftsociatotly,k
! - (unary minus)
2
sizeof ~ +tt - Right to,
*/ Left to R
Left to k
Left to R
Left to R
Left to k
7
Left to k
Left to K
10
| Left to Ri
&& Left to Ri
12
Left to Ri
13
?: Right to l
14
All assignment operators Right tol
15 (comma) Left to Rip
level in the list will be given precedencen
An operator which appears at a higher
the list.
which appears lower down in
[68]
Example3.21
Assumeiiis an int and f is afloat
variable. Then
Operation Result
Operation Result
i= 9/2
i= 9/2.0 f= 9/2 4.0
i= 9.0/2 f= 9/2.0 4.5
i=9.0/2.0 f= 9.0/2 4.5
4
i= 4/5 f=9.0/2.0 4.5
0
i= 4/5.0 f=4/5 0.0
i=4.0/5 f= 4/5.0 0.8
0
i=4.0/5.0 f=4.0/5 0.8
f=4.0/5.0 0.8
Example 3.22
int a;
float xl, x2, r;
double x3
r=(xl + x2/x3) / a;
"Before the above expression is evaluated, all the variables in the
to the highest order of the data in the expression. Thus the expressions will be promoted
above
after all the operands are promoted to double. The result willexpression will be evaluated
be evaluated as a double
variable. But it will be stored as a float because variable r has been declard as float.
Example 3.23
Study the following program
Program
#include <iostream.h>
#include <iomanip.h>
void main()
f
int a;
a=l;
cout<<endl<<when a=l then output is <<aK<endl;
a='C';
cout<<when a='C' then output is <<aKKendl;
a=5.2;
cout<<when a=5.2 then output is <<a<Kendl;
Run
When a=lthen output is 1
When a= 'C' then output is 67
When a= 5.2 then output is 5
Note that ASCIl value of Cis 67 and a is int variable, therefore, the statement a=C given
the output as 67.
[69]
3.14 Casting of Data
Sometimes you have to convert one type of data into another type.
you want to find the ratio of integer numbers a and b. The following
For example
you the desired result expression
m =a/b
where mis areal variable. Since a and bare both integer variables, the decimal
result of the division would be lost and ratio would represent a wrong figure.
of the desired result to operand m, you will like to convert one of the variablesFor a
parto
real numbers. This is known as casting. For casting of an integer
variable a into andb
f
assigM
have write (float) a.
Expression m = a /b may therefore be written as
m= (float) a / b;
The general form of acast is:
(data-type) expression
The expression may be a constant, variable or an
expression.
Example 3.24
Suppose that iis an integer variable whose value is 9, and f is a floating - point varia
whose value is 6.5. The expression
(i+f) %4
is invalid, because the first operand (i +f) is floating - point rather than
the expression integer. Howee
(int) (i+)) %4
force the first operand to be an integer and is therefore valid, resulting in the integer remainder
Self Check-3
1. What is the purpose of sizeof operator?
2. What is the purpose of comma (,)
operator?
3. Suppose x and y are two double type variables. Write a statement to add them
integers and assign to an integer variable.
Answers / Hints to Self Check-3
1. The s0zeof operator is a unary operator. This operator produces a result
in bytes, of data or data type that is the
specified.
2. Hint : () separator (i) combine expression (iii)
expression. produces a left-to-right evalual
3. Hint: int Result =(int) x + (int) y:
[70]
15 Standard Mathematieal Functions
The compiler supplios several mathematical functions that carry out frequently required
tasks. These functions are known as bult-in functions or standard functions or library
functions. Such tunctions have pre-dofined names. Each has an argumernt which is always
enclosed within parentheses. Several of these functions are summarized below. To use
anyof these functions in a program, we should include the line
inchude <math.h»
Function Purpose
Example 3.25
Program to find the area of a triangle using Hero's Formula!
Algorithm :
1. Input the three sides of the triangle : a, b, c.
2. Compute s = (a+b+c).2
3. Compute the area, area =Js(s - a)(s- b)(s -c)
4. Print area
5. STOP
[71]