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 a chain of 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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 6 activities on this page