4.4. Chained ConditionalsΒΆ
Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses:
The following program classifies a number (x) as positive, negative, or zero. Feel free to change the value of x to make sure it works.
1#include <iostream>
2
3int main () {
4 int x = -4;
5 if (x > 0)
6 {
7 std::cout << "x is positive\n";
8 }
9 else if (x < 0)
10 {
11 std::cout << "x is negative\n";
12 }
13 else
14 {
15 std::cout << "x is zero\n";
16 }
17}
Try changing the value of x above to see how the output is impacted.
Note
If you have adjacent if statements, the program will go through
executing each conditional, regardless if the conditions are met.
However, as soon as you add an else or even an else if statement,
the program will stop executing the chained conditionals as soon as a
condition is met.
These chains can be as long as you want, although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all the statements and squiggly-braces lined up, you are less likely to make syntax errors and you can find them more quickly if you do.
Q1
What will print after the following code is executed?
#include <iostream>
using namespace std;
int main () {
int x = 10;
if (x > 8) {
cout << "One! ";
}
if (x > 6) {
cout << "Two! ";
}
if (x > 3) {
cout << "Three!" << '\n';
}
return 0;
}
Q2
What will print after the following code is executed?
#include <iostream>
using namespace std;
int main () {
int x = 10;
if (x > 8) {
cout << "One! " ;
}
else if (x > 6) {
cout << "Two! ";
}
else {
cout << "Three!" << '\n';
}
return 0;
}
Q3
What will print after the following code is executed?
#include <iostream>
using namespace std;
int main () {
int x = 7;
if (x > 8) {
cout << "One! " ;
}
if (x > 6) {
cout << "Two! ";
}
if (x > 3) {
cout << "Three!" << '\n';
}
return 0;
}
Q4
What will print after the following code is executed?
#include <iostream>
using namespace std;
int main () {
int x = 7;
if (x > 8) {
cout << "One! " ;
}
else if (x > 6) {
cout << "Two! ";
}
else {
cout << "Three!" << '\n';
}
return 0;
}
More to Explore
if and comparison operators from cppreference