back


Nesting If Statments

You will often need to place IF statements inside each other. This is useful if you have two or more conditions that need to be met. For example, let's say you would only cut a class if you were both bored AND hungry. Just being bored wouldn't be enough...You could program it like this:

  IF (Bored)
    IF(Hungry)
       GUESS I'm gonna cut!
    ELSE
       I'm bored, but full. I can stay.
  ELSE
    I'm okay with this class today.
	 
	
As in most things with C++, there's more than one way to accomplish the same goal. You could do the same thing using the operators we learned about earlier. Nesting works, but you can quickly create a mess if you are not carefull. The important thing is to organize the levels of your nested IF statements so that you can keep track of which belongs to which. The basic rule is:

Match each ELSE with the last IF


C++ will still work if everything is lumped together...check out this example. However, this will drive you and anyone else who tries to read your code crazy. This is the same code, but organized.Take a look at this revised example.

Assignment
(To be checked out by me)
Write a program that uses three nested IF statements. Make it make sense and include comments in your program.