Skip to main content

Section 14.5 Nested Decisions

When designing your programs you may run into scenarios where it is useful to create nested decisions. Nested decisions describe the scenario of enclosing one decision into another. It may not seem intuitively obvious why this is necessary, but as your computer programs become more complex, it will be an extremely effective and useful strategy to consider.
Figure 14.5.1. Nested decisions allow for some neat program capabilities!
For example, consider the following flowchart, which describes an algorithm a new mother might use to stop her baby from crying:
Figure 14.5.2. Crying baby algorithm.
Notice how the “If the baby is wet” condition is nested inside of the “If the baby is crying” condition. That is what we mean by nesting! There is no difference in the way that you write the code. You just can put one if after the other. The only little trick to nesting is remembering that each if needs a corresponding end. When you have several nested decisions, it can get confusing which end keyword is referring to which if keyword. To help organize your code, MATLAB will automatically apply a tab after each if statement. That way you can see what “level” you are in.
For example, take a look at the code in figure 14.5.3 below. Keep in mind I do not expect you to understand what is happening in this code! (Spoiler: it is actually non-sensical code because I had to change some things to if statements so it didn’t include programming concepts you haven’t seen yet but that is not the point).
Figure 14.5.3. Example of non-sensical code of nesting.
You should be able to create a flow chart of this code from figure 14.5.3 alone. The key is to notice that on line 5, there is a nested if statement. Furthermore, there is a 2nd level nested if statement on line 13. The other thing that you should notice is that MATLAB has automatically applied a tab after each if statement.
Go ahead and type in some non-sensical code into MATLAB to see this auto-tab in action. Or you can just copy the code in figure 14.5.3.

Checkpoint 14.5.4. Nested If Statements and Flowcharts.

What is an example of when you would need to code using nested if statements? How would you make a flowchart for this example?
Think about nested if statements as a different sets of directions to get to a certain destination. How many "turns" does your example require?
Smart Indent
If you ever mess up your tabbing, don’t worry! Just select all your text, right-click, and select the “Smart Indent” option (see below). Again, this is something that you should try yourself.
Figure 14.5.5. Selecting text, right-clicking, and then selecting “Smart Indent” will fix any indentation problems your code has and will make it easier to read!

Checkpoint 14.5.6. Chapter Mantra.

You have attempted of activities on this page.