4.5. Nested ConditionalsΒΆ

In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:

This program classifies a number (x) as positive, negative, or zero, just like the program on the previous page. However, this time, we are using nested conditionals.

Classifying an Integer
 1#include <iostream>
 2using std::cout;
 3
 4void classify (int value) {
 5    if (value == 0) {
 6        cout << "value is zero\n";
 7    } else {
 8        if (value > 0) {
 9            cout << "value is positive\n";
10        } else {
11            cout << "value is negative\n";
12        }
13   }
14}
15
16int main () {
17    int x = 9;
18    classify (x);
19    x = x * -1;
20    classify (x);
21}

There is now an outer conditional that contains two branches. The first branch contains a simple output statement, but the second branch contains another if statement, which has two branches of its own. Fortunately, those two branches are both output statements, although they could have been conditional statements as well.

Note

There is not a limit to the number of times you can nest a conditional. However, you should try to limit this number, as it will reduce the complexity of your program structure.

Too many nested conditionals is considered a bad practice.

Notice again that indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. In general, it is a good idea to avoid them when you can.

On the other hand, this kind of nested structure is common, so it is important to be able read nested code, regardless of whether it is a best practice or not.

Q1

What will print?

#include <iostream>
using namespace std;

int main () {
  int x = 0;
  if (x == 0) {
    cout << "Hey!" << '\n';
  }
  else {
    if (x > 0) {
      cout << "Hi!" << '\n';
    }
    else {
      cout << "Hello!" << '\n';
    }
  }
  return 0;
}

Q2

What will print?

#include <iostream>
using namespace std;

int main () {
  int x = -4;
  if (x == 0) {
    cout << "Hey!" << '\n';
  }
  else {
    if (x > 0) {
      cout << "Hi!" << '\n';
    }
    else {
      cout << "Hello!" << '\n';
    }
  }
  return 0;
}

Q3

Your school uses a system to arrange students in a large stadium using their initials. Look at the function definition below. Where would a student with the initials "MZ" be seated?

string seating_arrangement(char first, char last) {
  if (last > m) {
    if (first > m) {
      return "Back Left!";
    }
    else {
      return "Back Right!";
    }
  }
  else {
    if (first > m) {
      return "Front Left!";
    }
    else {
      return "Front Right!";
    }
  }
}


More to Explore