Reputation: 3
Say I have a condition with 2 possibilities: a <= 10 and a > 10. I can use the if...else statement to printf() output 1 if a <= 10 or output 2 if a > 10.
But if I have a condition with 3 possibilities (like a <= 10, 10 < a <= 20, and a > 20) how do I write the program to printf() output 1 if a <= 10, output 2 if 10 < a <= 20, or output 3 if a > 20?
Upvotes: 0
Views: 152
Reputation: 881553
You just nest them, something like:
if ( a < 10) {
printf("1\n");
} else {
if (a < 20) {
printf("2\n");
} else {
printf("3\n");
}
}
or, provided the if
statements are the only things nested, you can get rid of quite a few braces:
if ( a < 10)
printf("1\n");
else if (a < 20)
printf("2\n");
else
printf("3\n");
Upvotes: 4
Reputation: 83527
You can still use an if...else
statement. The most obvious solution is to nest another if
in the else
clause. You can add a forth condition by nesting an if...else
instead.
This is so common that most languages provide an else if
option in order to avoid deep nesting when there are many possible conditions.
Upvotes: 1