0% found this document useful (0 votes)
14 views

C++ Operator

Uploaded by

Priyanshu Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C++ Operator

Uploaded by

Priyanshu Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

3

Operators And ExpressionS


:1 Introduction
An operator is a symbol or letter
used to indicate a specific operation on
aprogram. For example, the
symbol ' is an add operator that adds two data variables in
items called
operands.
An expression is a combination of operands (i.e. constants,
connected by operators and parenthesis. For instance, in the variables, numbers)
Aand B are operands and'+ is an operator expression given below,
A+ B
C+t supports many types of operators such as
expression that involves arithmetic operators is knownarithmetic, relational, logical etc. An
as arithmetic expression. The
computed result of an arithmetic expression is always a numerical
which involves relational and lor logical operators is called as value. The expression
computed result ofa boolean expression is always a logical value boolean expression. The
i.e. either true or false:
In C++ language, there are two types of
operators : operators inherited from C language
and new operators introduced by C++.
The operators introduced by C++ are as under:

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.

3.2 Arithmetic Operators


Arithmetic operators are summarized in table 1

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

Sign ofthe result is alwaysthe sign of the first


encethe operand.
21Integer Expressions
The Integer expressions are formed using Integer variables and/or Integer constants
connected by Integer operators e.g.
4 *5+5/2 - 9 %2
A+5- B*C + D %Ewhere A, B, C, D & E are integer variables.
Eor evaluation of Integer expressions the following rules are applicable.
1 .* and % operators have highest level of precedence and so these operators will be
operated first.
2. + and- operators have lower precedence and these operators will be operated later.
3. When operators have same precedence, the evaluation is carried out from left toright.
4. Parentheses will be used to overcome the precedence. The expressions within
parentheses will have the highest precedence and wil be evaluation first.
Example 3.1
Find the value of the following integer expressions.
1. 3*5 /2 + 6*9 %3 +2 * 3- 3

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

Example 3.2 expressions :


program to find the value of following integer
Write the
*3-3
I. 3*5/2 +6*9%3+2
2. 3*(5+2 *3) +25/(2*3+2)
Program
#include <iostream.h>
main()

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

3.2.2 Float Expressions


Float expressions is formed using Real/lnteger variable and/or
Real/ntegerco
connected by Real operators e.g.
4.5 * 2.0 + 5.0/2.0 + 15.75
Expressions.
The rule for evaluating Real Expressions is same as that of Integer
[52]
Examples3.3
Evaluate each of the following
(|25+2.5) * 2.0- (11.5 -; 2.5) expressi
/3.0 13.5
+
on.
(12.5+2.5)+ 2.0- (11.5-2.5)/ 3.0
4 13.5

15.0
9.0

30.0
3.0

5
27.0

40.5

23 Mixed Mode Expression


Ctt+ permits mixing of integer and real
may be called as mixed mode quantities in an expression. Such an expression
converted into the real value andexpression. In this mode, integer value is
always yield the real automaticaly
value.
Example 3.4
Assume A =4.5 I=l J =2 K=3 then
The value of the expression K/ J * (A +2.3 *1) is

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

LValues and RValues


The computer stores memory addresses of all the variables in the program. The8
of the variable is called lvalues and the content of that location is rvalue. Cons
following examples:
x= (8 + 9) *4;
The lett hand variables,
iatgnment statement is complete unless asingle lvalue is given.
xis called lvalues. The right
hand operand is
calledrva

[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.

3.3 Relational Operators


Relational operators and their meanings are shown in table 2.
Table 2

means Greater than


< means Less than
means Equals to
means Greater than or Equal to
<= means Less than or Equal to
!= meanS Not equals to

3.3.1 Relational Expression


An expression such as a <b containing a relational operator is termed as a ree
expression. The value of a relational expression is either true (one) or false
example

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

a&&h allb !(a)

Note that !(logical NOT) iS a unary operator.


Example 3.7
Ifx=60, y=200, b=2 and c=160 then
1. x<y is true
2. x+y <y is false
3. x*b== 120is true.
4. (r== 60) && (y >b) is true
5. (y!=60) |l(c >x) is true
6. ! (x >60) is true

Precedence of Boolean Operators is as shown in Table 5

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

Statement with Statement with

asignment operator shorthand operator


. X=*+7. *+=7

I=I-7 I-=7
X=x*y x *=y
x=xly x/=y
x=*%y

3.5.1 Advantages of the Shorthand Assignment Operators


Advantages of the shorthand assignment operators are :
1. Statement is more efficient.
2. What appears on the left hand side need not be repeated and theretore u
easier to write.
3. Statement is more easier to read
and concise.

3.6 Increment and Decrement Operators


C++ hastwo most useful operators'namely increment operator ++ and decremento
--, These operators transform a-variable into a statement expression that abbrev
special form of assignment. When used as a stand-alone expression, ++m andm
both equivalent to the assignment
[58]
m= m+ 1;
oimoly increase the value of m by 1. Similarly. the expression statements --m and
m--are both equivalent to the assignment.
m=n- 1;

theysimply decrease the value of mby 1.


However, when used in expressions, the pre-increment operation ++m is different from the
post-increment operation m++. The pre-increment increases the value of variable first
Pre using it in the expression, whereas the post-increment increases the value of the
variable only after using the prior value of the variable within the expression.
Example 3.9
(a) m= 7;
y=++m;

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;

is equivalent to the following statement


ifr>y)
m =X;
else
m=y;
Example 3.12
numbers.
Write a program to find the larger of two given
Flow chart is

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

produce by these operators is given in the table 8.


^ are binary operators. The output
, l and
TABLE 8

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

range of an int. Hence, after +


lies outside the
equivalent to decimal 65527, which
aIS yielding 9.
resumer at 32768,
32767, Counting
[63]
Self Check-2
substract 1 from the
1. Write four different C++ statements that each integer varia
of mand n after the execution
2. Assume m= 5, n=2. VWhat will be value of fol
expression.
m=n++;
3. Wite four unary operators.

Answers / Hints toSelf Check-2


1. m =m - 1

m- = 1;
m--;
--m;
2. m = 10, n = 3
3. ++, --, - (unary minurs), !

3.9 sizeof Operator


The sizeof is a unary operator. The sizeof operator is used to
the operand occupies in the main memory. The operand could return the number of b
be a variable, a constar
a data type. For example, the following
expression
n= sizeof(mean);
Would return the size occupied by variable mean.
Example 3.18
Study the following program

#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

Consider the following program

#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
int m = 50; llglobal variable
void main()

int m = 10; IMocal variable


clrscr();
cout<<m<<setw(5)<<i:m<<endl;

int m=20; IMocal to inner block


cout<<m<<setw(5)<<i:m<<endl;

cout<<m<<setw(5)<<::m<<endl;
getch();

Run
10 50 I/first cout
20 50 Il second cout
10 50 Il third cout

From this program,it is clear that :: m willalways refer to the global m.


The scope resolution operator is also used in a class member function definition and it is
also used to differentiate between numbers of base classes with identical names. It is
explained in detail in the chapter on "Classes and Objects".

12 Precedence in C++ Operators


The complete precedence relationship of all the operation discussed in this chapter are
given in the table 9.

[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

3.13 Automatic Type Conversion inC++


of different types in an expres
C++ permits mixing of constants and variables type conversion. If the operant
duringevaluation it adheres to very strict rules ofconverted to the 'higher type be
diferent types, the 'lower type is automatically to theirorder is given in
operation proceeds. The data in C++, ranked according
TABLE 10

Data Type Order

long double highest


double
float
unsigned long int
long int
int
short int
char lowest

[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»

In the beginning of the program.


Table 11 shows some common mathematical functlons.
TABLE 11

Function Purpose

sqrt (x) Vx(x>0) Square root of x


abs (x) absolute value of an integer nunber
fabs (x) absolute value of a real numser
sin (x) sine of x (r in radians)
cos (x) cosine ofx (x in radians)
tan (x) Tangent ofx (x in radians)
asin(x) sin-1 (x)
acos(x) cos-1(x)
atan (x) tan-1 ()
log (*) natural log of x (x>0)
logl0(x) Logarithm of number x to the base 10
exp (x) ex

pow(x,y) x raised to the power y

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]

You might also like