Advanced if Statements in C++

By: Priya Viewed: 153295 times  Printer Friendly Format    


It is worth noting that any statement can be used in an if or else clause, even another if or else statement. Thus, you might see complex if statements in the following form:

if (expression1)
{
    if (expression2)
        statement1;
    else
    {
        if (expression3)
            statement2;
        else
            statement3;
    }
}
else
    statement4;

This cumbersome if statement says, "If expression1 is true and expression2 is true, execute statement1. If expression1 is true but expression2 is not true, then if expression3 is true execute statement2. If expression1 is true but expression2 and expression3 are false, execute statement3. Finally, if expression1 is not true, execute statement4." As you can see, complex if statements can be confusing!

Listing below gives an example of such a complex if statement.

A complex, nested if statement.

1:  // a complex nested
2:  // if statement
3:  #include <iostream.h>
4:  int main()
5:  {
6:      // Ask for two numbers
7:      // Assign the numbers to bigNumber and littleNumber
8:      // If bigNumber is bigger than littleNumber,
9:      // see if they are evenly divisible
10:     // If they are, see if they are the same number
11:
12:     int firstNumber, secondNumber;
13:     cout << "Enter two numbers.\nFirst: ";
14:     cin >> firstNumber;
15:     cout << "\nSecond: ";
16:     cin >> secondNumber;
17:     cout << "\n\n";
18:
19:     if (firstNumber >= secondNumber)
20:     {
21:       if ( (firstNumber % secondNumber) == 0) // evenly divisible?
22:       {
23:            if (firstNumber == secondNumber)
24:                 cout << "They are the same!\n";
25:            else
26:                 cout << "They are evenly divisible!\n";
27:       }
28:       else
29:            cout << "They are not evenly divisible!\n";
30:     }
31:     else
32:       cout << "Hey! The second one is larger!\n";
33:        return 0;
34: }

Output: Enter two numbers.
First: 10

Second: 2

They are evenly divisible!

Analysis: Two numbers are prompted for one at a time, and then compared. The first if statement, on line 19, checks to ensure that the first number is greater than or equal to the second. If not, the else clause on line 31 is executed.
If the first if is true, the block of code beginning on line 20 is executed, and the second if statement is tested, on line 21. This checks to see whether the first number modulo the second number yields no remainder. If so, the numbers are either evenly divisible or equal. The if statement on line 23 checks for equality and displays the appropriate message either way.

If the if statement on line 21 fails, the else statement on line 28 is executed.



Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial