Decision Statements (IF)


So far we have seen statements that help you in repeating a particular task as long as you desire. Another important form of program flow control is to be able to make a decision as to how you want the program to continue. Statements of this kind are referred to as decision statements (sometimes also called selection statements).
The following topics are covered in this section:


If…Else If…else…

‘if-else’ is one of the decision statements available in C++. This enables the programmer to provide different paths for the program flow depending on certain conditions. For example: consider a program for dividing two numbers. Division by zero will lead to an error. To avoid this from happening, after obtaining the two numbers from the user the programmer will want to ensure that the denominator is not zero. Hence there needs to be two different program flow options. If the denominator is zero a message saying, "Division not possible" should be displayed. Otherwise the program should carry out the division and display the results. In simpler terms this can be stated as:

If the denominator is zero, then display a message and do not divide

else perform division and display the output.

Syntax:

The program flow is as follows: If the condition being tested within the ‘if’ statement is true, then the body of ‘if’ will be executed otherwise the body of ‘else’ will be executed. Thus the program takes a decision as to what it should do next.

You can also make use of the ‘if’ statement alone (‘else’ is not compulsory) or you can even make use of a series of ‘if...else’ statements as follows:

Example:

        // To find the greater among two numbers
        #include <iostream.h>
        int main( )
        {
            int a, b;
            cout<< "Enter the two numbers you want to compare : ";
            cin>>a>>b;
           if (a = =b)
           {
                  cout << "The two numbers are equal";
            }
            else if (a>b)
            {
                  cout <<a<< " is greater than "<<b;
            }
            else
            {
                 cout << b<< " is greater than "<<a;
            }
            return 0;
        }

In the above program, we have used a series of ‘if…else’ statements. The first condition is:

if (a = =b)

so the program will check whether ‘a’ is equal to ‘b’. If it is equal then the body of the ‘if’ statement will be executed. Once the statement is executed, the compiler will not bother about the next ‘else if’ and ‘else’ statements because one condition has been satisfied. Program flow will then go to return 0;

If the first ‘if’ condition is not satisfied, the program control will go to the following ‘else if’ statement:

else if (a>b)

Even if this is not satisfied then only will it go to the next statement, which is an ‘else’ statement. Since ‘a’ was not greater than ‘b’, and equality was also tested earlier the only possibility is that ‘b’ is greater than ‘a’. Thus if the first two conditions have failed then the program flow will go to the body of the ‘else’ block.

Remember: Using the ‘if…else..if’ format, only one of the bodies will be executed (not all). If one condition is satisfied the rest of the ‘else..if…else’ is ignored.

When we use the ‘if..else if’ construct, if one of the conditions is satisfied that corresponding body will be executed and the rest will be ignored. But what would happen if we use a series of ‘if’ statements alone?

        #include <iostream.h>
        int main( )
        {
            char letter;
            cout<<"\n Enter the alphabet 'a' or 'A': ";
            cin>>letter;
            if (letter= ='a')
           {
                cout<<"\n You entered an 'a'";
            }
            if (letter= ='A')
            {
                 cout<<"\n You entered an 'A'";
            }
            return 0;
        }

In the above program, the compiler will check for ‘a’ first and then it will check for ‘A’ also. Even if the first condition is satisfied, it will still check for the second ‘if’ condition. In such cases it would be better to use the following:

Now if the user enters an ‘a’ then the program will not enter the ‘else if’ statement to check whether the letter is an ‘A’.

Remember: It is better to make use of ‘if-else-if’ instead of a series of ‘if’ statements because in that way your program need not check all the conditions unnecessarily.

And whenever you use a series of ‘if-else-if’ statements, test the condition that is most likely to be true first (so that the program need not waste time in checking more conditions).


Nested If

You can have an ‘if’ statement within another ‘if’ statement. This is known as nested ‘if’. The program flow will enter into the inner ‘if’ condition only if the outer ‘if’ condition is satisfied. In general form nested ‘if’ will be of the form:

There can be more than one ‘if’ condition (i.e. you can nest as many ‘if’ statements as you want). An example code fragment is given below (‘month’ and ‘year’ are integer variables whose values are obtained from the user):

if (month= =2)
{
cout<< "The month is February";
    if ( (year%4) = = 0)
    {
        cout<< "This month has 29 days.";
    }
    else
   {
        cout<< "This month has 28 days.";
    }
}

In the above code fragment, only if the variable ‘month’ is equal to 2 will the program enter into the ‘if’ block. Within this block it will print:

The month is February

Then it will check as to whether the given year is a leap year or not. If it is a leap year then it will display that the month has 29 days else it will say the month has 28 days.

Empty ‘if’ statement:

We have seen the use of empty ‘for’ statements but empty ‘if’ statements might not be useful. In fact empty ‘if’ statements are usually logical error (because the programmer places the semi colon by mistake at the end of the ‘if’ statement).

Example:

if (num1<num2);
{cout<< "num1 is less than num2";}

Since the ‘if’ statement has been terminated the display will be produced irrespective of the values of ‘num1’ and ‘num2’.

Checking multiple conditions:

In mathematics you will encounter expressions such as: 30<y<40. This actually means that the value of ‘y’ is greater than 30 and less than 40. In C++ you cannot use such an expression directly. You cannot write:

if (30<y<40)

because you cannot cascade relational operators. You have to mention the conditions separately and combine them using the logical operators.

if ( (30<y) && (y<40) )


Conditional Operator (?:)

The conditional operator is a ternary operator and this operator is an alternative to ‘if…else’ statements. The syntax is as follows:

test-condition ? value1 : value2;

The test condition will be evaluated and if it is true then ‘value1’ will be the value for the expression. If the condition is false then ‘value 2’ is the value for the entire expression. For example consider the coding:

The value of y will be 20 because ‘a’ is not greater than ‘b’. This sort of expression can be written using the ‘if’ statement as:

Beware: It’s just that you could reduce the amount of coding by using the ternary operator. Be careful that you don’t confuse the logic while trying to reduce the length of the code!


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.