Various C++ Operators


 In this section I shall describe some of the various operators that are used in C++.

 1.    Arithmetic Operators : 

These are operators that perform basic mathematical operations like addition, subtraction, division and multiplication.
Addition                       :           +
Subtraction                   :           -          
Multiplication                :           *
Division                                  /

There is also one more arithmetic operator known as modulo operator (%).
This operator is does not find percentage. It is used to find the remainder after division.
For example : 6 % 4 = 2 (because dividing 6 by 4 gives a remainder of 2).
The modulo operator can operate only on integers.
Arithmetic operators need two quantities to perform an operation. Hence they are called binary operators.

#include <iostream.h>

int main( )

{

int num1, num2;

cout<<"Enter the two numbers : ";

cin>>num1>>num2;

cout<<"The product is : "<<num1*num2;

cout<<"The sum is : "<<num1+num2;

cout<<"The difference is : "<<num1-num2;

cout<<"The quotient is : "<<num1/num2;

cout<<"The remainder is : "<<num1%num2;

return 0;

}

In the program, we declare two integers ‘num1’ and ‘num2’. We obtain their inputs using the statement:

cin>>num1>>num2;

Thus is a method of obtaining multiple inputs in one line of coding. The above statement is equivalent of:

cin>>num1;

cin>>num2;

The input is given by using a space between the two numbers or you can press enter after the first number and then enter the second number. The rest of the lines are used to find the various results using the two numbers.

When you run the program you would get the following on your screen:

Enter the two numbers : 8 4

The product is : 32The sum is : 12The difference is : 4The quotient is : 2The remainder is : 0

Something is not right in this output; the results are fine but the display is continuous. To make the display in an organized manner, you should tell the compiler to print the outputs on the next line (instead of printing all the results on the same line, as done above).

For this purpose C++ provides us with what are called as escape sequences.

Escape Sequences:

If you remember, whatever you type within double quotes after cout<<, will be printed just as it is. There is a problem in case you want to print a new line, or you want to use tabs (because whatever you type, the compiler will print it out).

To solve this problem, escape sequences were developed. Just as the name implies, these escape sequence characters are used to escape from the normal sequence of events.

An escape sequence always begins with a backslash ( \ ). For a new line, the escape sequence is: \n (n for new line).

If you want to push the tab setting then use \t (t for tab).

The modified program for doing simple arithmetic operations is as follows:

#include <iostream.h>

int main( )

{

int num1, num2;

cout<<"Enter the two numbers : ";

cin>>num1>>num2;

cout<<"\n The product is : "<<num1*num2;

cout<<"\n The sum is : "<<num1+num2;

cout<<"\n The difference is : "<<num1-num2;

cout<<"\n The quotient is : "<<num1/num2;

cout<<"\n The remainder is : "<<num1%num2;

return 0;

}

When you run the program you would get the following on your screen:

Enter the two numbers : 8 4

The product is : 32

The sum is : 12

The difference is : 4

The quotient is : 2

The remainder is : 0

There are a few other useful escape sequence characters as well:

Try it: Use the above escape sequences in a C++ program to see their effects. The \a escape sequence will literally make a sound of a bell (if you have a sound card and speakers attached to your system).

Remember: Escape Sequences always start with a backslash ( \ ) and have to be followed by valid characters (like n, a, t etc…). If you happen to use some other character (like w), the compiler will display a warning message (the program will run and usually the compiler will ignore the character or simply display the character on screen).

Coming back to the program with arithmetic operators; what would happen if I were to give an input of 5 and 2 as the two numbers? What will the quotient and remainder be? The result will give a quotient of 2 and a remainder of 1. But isn’t 5/2 = 2.5??? Why doesn’t it calculate that way?

The answer lies in the declaration of num1 and num2. Since these two variables are declared as integers, all the results of arithmetic operations are also in integer format. Suppose you declared num1 and ‘num2’ as floating point data type, then you would get an output of 2.5 as the quotient. In this case, what about the remainder? Is it zero always?

Remember: The modulo (%) operator can operate only on two integers and not on any other data type. So if you use floating numbers, the compiler will give you an error. The other arithmetic operations can be performed on integers as well as floating point variables.


2.    Assignment Operators :
Assignment operator is something that assigns a value to something else.
The easiest example is the equal to sign. As you all know it is denoted by = .
Example : When you say x = 1, the value to the right of equal is assigned (given) to the term on the left, i.e. one is assigned to the variable x.
 

You always assign a value to some variable. 2 = x; is a wrong statement because you cannot assign the value of x to 2.

Of course, the value on the right can be an expression like below:

Multiple assignments can also be made in C++ (i.e more than one variable can be assigned a value at the same time). Example: Suppose x, y and z have been declared as integers, then

x = y = z = 3;

is an example of multiple assignment. The process of assignment will be from right to left; 3 is assigned to z and the value of z (which is now 3) is assigned to y and y’s value is assigned to z. The above multiple assignment is equivalent to the following set of statements:

Is this valid? x = y+1 = 3;

This sort of a statement is not valid in C++. You cannot use arithmetic operators in between multiple assignments.


3.    Assignment Arithmetic Operator :

+ =        - =       * =    ,     / =

 Assignment arithmetic operator is one that performs an arithmetic operation as well as does assignment.
Consider the example :
X + = 3
When the compiler reads this, he knows that the above expression is the same as :
X = X+3
i.e., the value of X is incremented (increased) by 3 and the new incremented value is assigned to X. So if X was 2 before this expression, then it will be 5 after this expression is executed (performed).

In the same way you can make use of -=, *= and /=. In other words:

var1 - = var2 is the same as

var1=var1 - var2

 


4.    Relational Operators :

<    ,     >    ,     = =        ! =        >=        <=

! = stands for not equal. Actually the exclamation mark ( ! ) means ‘NOT’.
Relational operators are also binary operators (meaning that they operate on two operands). They are used for comparing two values. The result of the comparison is true (value 1) or false (value 0).

Some examples are given below:

5>4     is    True    =        1

3>2     is    False   =         0

In programs that you write, comparisons will usually be made between one variable with a number or between two variables. Example:

x>y

z>10

> is for greater than while >= stands for greater than or equal to.

x>=y

will yield a true value even if x = y. Whereas x>y will yield a false value when x = y. Be clear as to what relation you want to test when using these operators.

Suppose you want to test whether two variables are equal, you have to make use of the equality operator. The equality operator is denoted by = = (double equal to signs).

Remember: Many beginners in programming mix up the use of the equality operator and the assignment operator. The assignment operator is a single equal to sign and it is meant only for assigning values to variables. The equality operator is used to compare whether two values are equal.

We’ll see a simple program for comparing two numbers and displaying the appropriate result.

#include <iostream.h>

int main( )

{

float num1, num2;

cout<<"Enter the two numbers : ";

cin>>num1>>num2;

if (num1>num2)

{

cout<<"The number "<<num1<<" is greater than "<<num2;

}

if (num1= =num2)

{

cout<<"The number "<<num1<<" is equal to "<<num2;

}

if (num1<num2)

{

cout<<"The number "<<num1<<" is less than "<<num2;

}

return 0;

}

 

I still haven’t covered the topic on ‘if’ conditions but you should be able to understand the working of the above program. The two numbers that are obtained from the user are compared using three ‘if’ conditions. Depending on which condition is satisfied, the corresponding output will be displayed.

I just wanted to stress on the relational operators used (particularly the equality operator). Many beginners will type the above coding as given below:

#include <iostream.h>

int main( )

{

float num1, num2;

cout<<"Enter the two numbers : ";

cin>>num1>>num2;

if (num1>num2)

    {

    cout<<"The number "<<num1<<" is greater than "<<num2;

    }

if (num1 = num2)         // BEWARE OF THIS MISTAKE

    {

    cout<<"The number "<<num1<<" is equal to "<<num2;

    }

if (num1<num2)

    {

    cout<<"The number "<<num1<<" is less than "<<num2;

    }

return 0;

}

What do you think will happen? Let’s follow the program just like the compiler. Two numbers ‘num1’ and ‘num2’ are obtained as input from the user. Then the first condition to check is whether num1 is greater than num2. Let us assume that the two numbers are 7 and 5. Hence num1>num2 and the output will display:

The number 7 is greater than 5.

Next the compiler will see the second if condition. In this if condition it encounters the statement:

num1=num2

The compiler assumes that this is an assignment and not a comparison (because the assignment operator has been used). The result??? In this line of coding, the compiler will assign the value of num2 to num1 (because num2 is on the right of the assignment operator). Num2 has a value of 5 and num1 is also set to 5. The compiler will also execute the cout statement within that if condition and hence you will also get the output as:

The number 5 is equal to 5

Thus the final display on the screen will be:

The number 7 is greater than 5 The number 5 is equal to 5

I think this should give you a good idea as to how wrong a program could go just because of one simple sign being forgotten. The problem is that many users don’t understand the difference between an assignment and equality operator. Just remember that the compiler is not clever enough to understand what you have in your mind. It needs a way to differentiate between assignments and comparisons and hence it relies entirely on the = and = = difference.

The above program was a short one and it was easy to find the problem. Just imagine a program with 100s of lines of coding containing one small mistake like that done above

I shall deal with the if statement in another chapter; but for the time being just remember that whatever you type within an ‘if’ condition will be executed if the ‘if’ condition is true. Maybe it’s a bit confusing here; I’ll explain in detail later on, don’t worry.

One more point to note. In the following program, we have asked the compiler to display the result of num>5. Do you think it is valid?

int main ( )

{

int num;

cout<< "Enter the number";

cin>>num;

cout<<(num>5);         //Legal???

return 0;

}

Always remember that the result of a comparison yields a value of TRUE (1) or FALSE (0). Hence the above program is perfectly correct. In case you enter a value that is greater than 5 you will get the output as 1 else you will get 0.


5.    Logical Operators :

AND ( && )                   OR ( || )                 NOT (!)

          AND : it combines two conditional expressions and evaluates to be true only if both conditions are fulfilled.

            Example :
             // TO CHECK WHETHER THE GIVEN NUMBER IS EVEN
           # include <iostream.h>
  
     int main ( )

{
                int num;
                cout<< “Enter the number”;
  
         cin>>num;
  
         if ( (num != 0) && ( (num % 2)= = 0) )         // THE TWO CONDITIONS HAVE TO BE SATISFIED
  
                     {
  
                         cout<<”Even Number”;            // WHEN BOTH ARE SATISFIED THE NUMBER IS EVEN
  
                      }
            return 0;
           
}

            OR : operator combines two condition expressions and evaluates to true if any one of the conditions is fulfilled.

NOT: NOT is a unary operator. Unlike AND and OR, NOT operates only on one operand. The logical value of the operand is reversed. If the operand is true, then after the NOT operation it will be become false. You might be thinking that the NOT operator can operate only on 1 and 0. Actually, any number greater than 0 will be considered as a true value. Hence the following would give:

!5 is actually 0

!0 will give a result of 1

!1 is equal to 0.

Basically, any number other than zero is considered as true. So not of any number will give you FALSE (or zero). Check out the following program that illustrates the NOT operator.

#include<iostream.h>

int main ( )

{

int num, result;

cout<< "Enter the number";

cin>>num;

result = (!num);

cout<<result;

return 0;

}

If you run this program you will obtain the results that I mentioned earlier.


6. Unary Operators : (NOT, increment operator ++, decrement operator --)

 Unary operators operate on only one operand which can be constant or a variable. The increment operator can be used in two ways.

            If we write :   i1 = 10;
                                
i2 = ++ i1;
This is the same as :
 i1 = 10;
i1 = i1 + 1;
i2 = i1;
At the end of these steps the value of i1 and i2 will be 11.

  BY USING IT AS A PREFIX, INCREMENTING IS DONE FIRST AND THEN ASSIGNING IS DONE

If we write :   i1 = 10;
                               
i2 =  i1 ++ ;
         
This is the same as :

  
                         i1 = 10;
                                  i2 = i1;
  
                             i1 = i1 + 1;
At the end of these steps the value of i2 will be 10 and that of i1 will be 11.

  BY USING IT AS A SUFFIX, ASSIGNMENT IS DONE AND THEN INCREMENTING IS DONE.

 The decrement operator works in the same way. The only difference is that it decreases the value of the operand by one.


Go over to the next section on : Loops

Or go back to the Contents.


Copyright © 2002 Sethu Subramanian All rights reserved.