Professional Documents
Culture Documents
4.1 INTRODUCTION
We know that its result is 2. But how is that result calculated? We first multiply 2 and 3
and then subtract the product (6) from 8. That means that multiplication has higher priority
or precedence than the minus, otherwise if we first subtract 2 from 8 and then multiply the result
would be 18. Each operator has a precedence level which decides its turn for operation when
there are several operators in a statement. The operator with highest precedence is performed first
followed by the one with the next lower precedence. The precedence levels of the operators are
set in the complier and computer follows these rules during calculations.
Now if a number of operators having the same precedence level are there in a statement then
how to decide as to which should be performed first. For example consider the following
calculation.
20 % 3 * 5
The operators % and * have same level of precedence and both are binary operators. In the
previous chapter we studied the modulus operator (%) which gives the remainder on division. Thus
20 % 3 = 2. In the above expression, if operation 20%3 is performed first the result is 10, otherwise
if 3*5 is performed first the result is 5 because in that case 20 %15 = 5. In such cases the
associativity of the operators comes to rescue. Since the operators are binary if the operations are
performed left to right the result is 10 and if it is performed right to left the result is 5. The
associativity of both % and * operators is left to right and thus the correct result is 10.
The operators in C++ are implicitly defined for variables of fundamental types. For user
defined types such as class objects, C++ allows to redefine their functionality so that they can
be used for class objects as well. The examples are (i) manipulations of vectors, (ii) manipulation
of complex numbers, etc. For such cases the operators are overloaded (functionality is redefined)
Even if the functionality of an operator is redefined (see Chapter 13 ) the arity, the precedence
and the associativity of the operator do not change.
The basic assignment operator is ( = ) which is often called equal to. On the left of this operator
we write the name of variable to which a value is to be assigned or l-value and on right side we
write the value to be assigned to it or r-value. The l-value is the memory space in which the r-
value is stored. Consider the following assignments.
int x = 5; // Declaration and initialization
int y = 10;
y = x ; // assignment
In the last statement, will the value of x be assigned to y or the value of y be assigned to x?
The associativity of = operator is right to left, so value of x will be assigned to y. In this operation
y becomes 5.
In the previous chapters we have already studied the two methods of declaration and
initialization, which are illustrated below.
type identifier = value ;
type identifier ( value) ;
Operators 79
Similarly a string of characters may be assigned. In the following the <string> header file is
included in the program in order to declare variables of type string.
#include<string>
void main()
{string myname ; // myname is a variable of type string
myname = Monika; /*Monika is the value assigned to myname */
string Name (Sujata); // Name is assigned value Sujata
string name = Mamta; }
However, if the header file <string> is not included, a string variable may be declared as C-
string. For such a case the assignment is illustrated below.
char myname [] = Monika;
The constant 0 (zero) is of type int, however, it may be assigned to variables of all types.
Thus we can write as below.
80 Programming with C++
int x = 0; // It assigns 0 to int x.
float y = 0; // It assigns 0.0 to float y
double d = 0; //It assigns 0.0 to double d
char ch = 0; //It assigns Null character \0 to ch,
Programs 4.1 and 4.2, given below, illustrate the assignment of different types of variables.
#include <iostream>
using namespace std;
Operators 81
void main()
{int P(20); // This is equivalent to int P = 20;
int M = 30;
cout<<P = <<P<<,t M = <<M<<endl;
double C (4.56), D ; // double C(4.56) is equivalent to
// double C = 4.56
D = 6.54;
cout<< C = << C<<,t D = <<D<<endl;
P = 20, M = 30
C = 4.56, D = 6.54
Kh = B, ch = A
The following program makes use of <string> header file which provides similar assignment
operations as we do for int or char variables.
PROGRAM 4.2 For a string of characters we may use class string (see Chapter 17).
#include <iostream>
using namespace std;
#include <string>
void main()
{ // In following Name1, Name2 and Name3 are names of strings.
string Name1(Mona Lisa); // string of characters have to be
// put in double quotes
string Name2 = Gyatri;
string Name4 = Malhotra;
string Name3;
Name3 = Raman; //Assignment = can be used for objects
//of class string.
cout << Name1 = << Name1 <<endl;
cout << Name2 = << Name2 <<endl;
cout<< Name3 = << Name3 <<endl;
cout << Name2 + Name4 = << Name2 + Name4<<endl;
}
82 Programming with C++
The expected output of the program is given below. Note that we have used header file <string>
in the program. The objects of this class may be added as illustrated in last line.
Name1 = Mona Lisa
Name2 = Gyatri
Name3 = Raman
Name2 + Name4 = Gyatri Malhotra
We have already discussed the arithmetic operators in Chapter 3. The different arithmetic
operators are +, , *, / and % which represent the addition, subtraction, multiplication, division
and modulus. The application of these operators has also been illustrated in Program 3.13 in the
previous chapter. The operator % is applicable only to integers and is generally used to test the
divisibility of a larger integer by a smaller integer. If on division the remainder is zero then larger
number is divisible by the smaller number. The following program illustrates the test of
divisibility.
#include<iostream>
using namespace std;
void main()
{ int A,B, m;
The expected output is as under. Two numbers 64 and 2 are entered. 64 is divisible by 2.
Enter two integers :64 2
you have entered A = 64 and B = 2
A is divisible by B
The following program calculates the roots of a quadratic equation ax2 + bx + c = 0. Because
this involves the evaluation of square root so the header file <cmath> is included in the program.
Operators 83
PROGRAM 4.4 The program calculates roots of a quadratic equation.
#include <iostream>
#include <cmath> //<cmath> header file is required for
//calculating square root
using namespace std;
int main()
{ // quadratic equation is: a x2 + bx + c = 0
double a,b,c, P, S;
cout << Enter the values of a,b and c :;
cin>>a>>b>>c;
P = b*b-4*a*c ;
cout <<Root R1= << (b+ S)/(2*a) <<, and Root R2 = << (b
S)/(2*a) <<endl;
}
return 0;
}
The following two trials of the above program are carried out with different values of a, b and
c. In the first case imaginary roots are obtained and in second case real roots are obtained.
Enter the values of a,b and c :4 10 10.25
Root R1 = 1.25+i1 and Root R2 = 1.25i1
The following real roots are obtained when we enter a = 4, b = 10 and c = 4.
Enter the values of a,b and c :4 10 4
Root R1= 0.5, and Root R2 = 2
#include <iostream>
using namespace std;
int main()
{
int a = 15, n = 3,s = 8, p = 6,r = 3,A ,B , P1,P2,P3 ;
double C,D;
A = n*a%p ; // here first n and a are multiplied before
//the operation of %.
B = n*(a%p); // here () is evaluated first and the result
//is then multiplied to n.
P1 = n% a*p ;
P2 = (n%a)*p ;
P3 = n%(a*p);
A = n * a % p ;
Though the precedence level of * and % is same but evaluation is from left to right so the
above expression is equivalent to the following.
A = (n * a) % p ;
Therefore, the expressions A = (n * a) % p; and A = n *( a % p); would not give same
result. Same is true for evaluation of P1, P2 and P3. The expression P1 = n%a*p ; is equivalent
to the following.
P2 = (n%a)*p ;
But P3 = n%(a*p); is different because the priority has been changed. In this the expression
(a*p) is evaluated first.
C++ allows combining the arithmetic operators with assignment operator. The arithmetic
operator is written first followed by assignment operator but not vice versa. Thus we write the
code for add and assign as below,
B += 6;
which means that first add 6 to the present value of B and then assign the result to B. This is
equivalent to the following statement.
B = B + 6;
Similarly the other operators may also be combined. All the composite operators are listed
in Table 4.3. The applications of some of these are given in the Program 4.6.
86 Programming with C++
In all the composite operators there should not be any space between the symbols. For instance,
if we give space between + and = such as + = it may result in error.
The expected output is given below. The out put is self explanatory.
m = 5, n = 16, p = 2, s = 3
q = 3
For increasing and decreasing the values of integral objects by unity, we may make use of
increment operator ++ and decrement operator respectively. These operators may be placed
before or after the variable name. When the operators ++ and are placed before the variable
name, these are called pre-increment and pre-decrement operators respectively. When the
operators are placed after the names then these are called post-increment and post-decrement
operators. In case of pre-increment the present value of variable is first increased by unity and
the incremental value is then used in the application. And in case of post-increment, the present
Operators 87
value of variable is used in the application and then the value of variable is incremented. Same is
the case of operator . The pre and post versions of ++ and are also elaborated in Table 4.4.
Also take care that there should not be any space between ++ or between because this may
result in error.
Table 4.4 Increment and decrement operators
#include <iostream>
using namespace std;
int main()
A = 6*++n ;
cout << A = <<A <<\t n = <<n <<endl;
K = 5*a ;
cout<<K = <<K<<\t a = <<a << endl;
B =r++*r++ ;
cout<< B = <<B<<\t r = << r << endl;
C = p *p ;
cout<<C= << C<<\t p= << p << endl;
return 0;
}
The expected output given below is self explanatory. However, it is also explained.
A = 36 n = 6
K = 30 a = 5
B = 9 r = 5
C= 16 p= 2
88 Programming with C++
For the first line of output n = 5. The n is first incremented to 6 and then multiplied by 6
to give 36. The second line of output is obtained by multiplication of 5 with the initial value
of a, which is 6. The variable a is then decremented to 5. The third line is obtained by
multiplying r with r, taking the initial value. Then r is incremented twice. The last line of output
is obtained similarly. The program below illustrates more such cases.
#include <iostream>
using namespace std;
int main()
{int m=6,n=2,p=4,r=3,s=8,k = 4,a,b,c,d ;
a =++n+ ++m;
b = s++ * s++;
c = p *p ;
d = ( k* k)*++r ;
cout<<a = <<a<<,\tn = <<n<<,\tm = <<m<<endl;
cout<<b = <<b <<,\ts = <<s<<\n;
cout<<c = <<c<<,\tp = <<p<<endl;
cout<<d = <<d <<,\tk = <<k<<,\tr = <<r<<endl;
return 0;
}
A = ++n * n ;
The result is A = n*n ; with the initial value of n, because ++ and have higher precedence
than *. But if you have an expression like
A = ++n * p* n;
It would evaluate as A = (n+1) *(p1)*(n1);
The following program involves product of three factors like the example given above, and
it is interesting to note the results. Would you like to explain the results?
PROGRAM 4.9 Illustrates use of operator ++ and in along with other operators.
#include <iostream>
using namespace std;
int main()
{
int a = 6, n= 5,s =8, p=4,r=3,A,B,C,K,M,D,E ;
A = ++n* p * n ; // Equivalent to 6*3*5=90 and now p = 3
cout << n = <<n <<, A = <<A <<endl;
B = ++a*2* a; // This is equivalent to 7*2*6
D = a * ++a ; // This is equivalent to 6*6
E = ++a* a*++a; // Equivalent to 6*6*7 = 252
cout<<B = <<B<<, a = <<a << , D = <<D <<, E = << E
<<endl;
These operators are used to compare two variables and are generally used with conditional
statements. For example, the code if(A==B) means if A and B are equal. Note that in this two
equal to signs (==) are used. Programmers often make a mistake by using single =. The other
relational operators are explained in Table 4.1. These are explained as well as their applications
are illustrated in Chapter 5.
90 Programming with C++
Boolean operators are logical operators. They relate the logical statements. Let A and B be the
two variable representing two logical statements. The logical variable have only two states that
is either it is true or false. If it is true the variable has a value 1 or a positive value. If it is false it
has value zero. The three Boolean operators are OR, AND and NOT. Table 4.5 gives details
about these operators and their symbols.
Table 4.5 Boolean Operators
The evaluation of various conditions in terms of true or false in different situations are given
in Table 4.6(a,b,c) below.
#include <iostream>
using namespace std;
int main()
{ int p, q, r, s,t,x, y, z;
p =1;
Operators 91
q = 0;
r = 1;
s = p||q;
t = !q;
x = p&&q;
y = (p || q && r||s);
z = (!p || !q && !r || s);
The expected output given below should be verified by reader by calculations with help of Table
4.7(a,b,c).
s = 1, t = 1, x = 0
y = 1, z = 1
As already discussed in Chapter 1, a bit is the basic unit of memory. It can have only two states.
If it is set its value is 1 otherwise it is zero. Bitwise operation means convert the number into
binary and the carry out the operation on each bit individually. For example let us take the
operation complement represented by symbol (~). Let us take a number
short A = 42;
A short number is stored in two byte or 16 bits. Therefore,
A when expressed in binary = 00000000 00101010
Complement of A is ~A = 11111111 11010101
The compliment operator changes the bit with value 0 to 1 and the one with value 1 is
changed to 0. The different bitwise operators are listed in Table 4.7 below. It also illustrates
codes.
Table 4 .7 Bitwise operators
Contd...
92 Programming with C++
|= Bitwise OR assign A |= B;
^= Bitwise XOR assign A ^= B;
<<= Bitwise shift left assign A <<= 2;
Shift left by 2 places and assign to A
>>= Bitwise shift right assign A >>= 1;
Shift right by 1 place and assign to A
The operators AND, OR and XOR are explained in truth Table 4.8 below.
Table 4.8 Bitwise operators AND, OR and XOR
The programs given below explain the application of some of these operators.
PROGRAM 4.11 Operator complement (~) is used to determine the maximum value of
an integer that can be stored on my PC.
#include<iostream>
using namespace std;
void main()
{ unsigned A = 0;
A = ~ A;
cout << A = <<A <<endl;
}
#include<iostream>
using namespace std;
void main()
{ short A =24;
Operators 93
short B = 8;
int C = A&B;
cout << C = <<C <<endl;
}
The expected output is given below.
C = 8
The output is explained as below. A short number is stored in two bytes, therefore,
24 in binary is equal to 00000000 00011000
8 in binary is equal to 00000000 00001000
Bitwise AND is equal to 00000000 00001000
The result 0000000000001000 in binary is equal to 8.
The following program illustrates OR and left shift operators.
#include<iostream>
using namespace std;
void main()
{ short A =42;
short B = 12;
int C = A|B;
int D = A<<1;
#include<iostream>
using namespace std;
void main()
{short A =42;
short B = 12;
short C = 24;
short D = A^B; // XOR operator
C <<= 1;
A <<=2; // Shift to left by 2 places and assign
B >>=2 ; // shift right by 2 places and assign
cout<< A = <<A<< \tB = << B <<endl;
cout << C = <<C <<endl;
cout << D = << D <<endl;
}
The binary equivalent of A = 42 has been shifted two places to left. So the number gets
multiplied by 4. So A = 168. Similarly the right shift by two places in case of B divides it by
4.The binary equivalent of 24 has been shifted to left by one place and assigned to C. Therefore,
C = 242 = 48. For A ^ B see the following explanation.
Binary equivalent of 42 is 00000000 00101010
Binary equivalent of 12 00000000 00001100
Bitwise XOR operation gives 00000000 00100110
This is equivalent to 38.
The following Program illustrates more of the compound assignment operators.
PROGRAM 4.15 Illustrates the application of operators ^=, &= and |=.
#include<iostream>
using namespace std;
void main()
{ short A =20, D , E, F;
short B = 18;
short C = 30;
D = C^=B;
E = A &=B ;
F = C|=A ;
Operators 95
cout <<E = <<E <<endl;
cout <<F = << F <<endl;
cout << D = <<D <<endl;
}
Chapter 18 deals exclusively with operations on bit sets based on functions in <bitset> header
file.
Precedence is an important aspect of operators. A partial list of operators and their precedence
is given in Table 4.9. The table does not include all the operators because we have not so far dealt
with them. For a more detailed list see Appendix C.
Table 4.9 A partial precedence table. Those higher in list have higher precedence