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.

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.


More to Explore

You have attempted of activities on this page