Main content
AP®︎/College Computer Science Principles
Course: AP®︎/College Computer Science Principles > Unit 3
Lesson 5: ConditionalsNested conditionals
Computer programs use conditionals to select the correct path for a program to go down. When a program only selects one of two paths, it can use a simple conditional (if/else). When a program selects one of many paths, it can use nested or chained conditionals.
Nested conditionals
Imagine a program that reports whether a number is positive, negative, or zero. That program needs to select from 3 paths.
The flowchart for the logic could look like this:
We can translate that into JavaScript using nested conditionals. Here's the equivalent JS:
var numberSign;
if (number > 0) {
numberSign = "positive";
} else {
if (number < 0) {
numberSign = "negative";
} else {
numberSign = "neutral";
}
}
Our outer conditional is a simple
if
/else
, corresponding to the top diamond in the flowchart. Then inside the else, we nest an inner conditional corresponding to the second diamond in the flow chart.In text-based languages like JavaScript, it's important to pay attention to the syntax and formatting of your nested conditionals. Notice how I use curly brackets around every set of instructions and indent the inner conditional inside the
else
. That helps other programmers (including future me!) better understand the flow of the logic.✏️ The program below compares the scores of two players and determines who has won, loss, or tied. Try changing the values around so that each player wins.
Alternate nesting flows
For most nested conditionals, there are many possibilities for the order of the various conditions.
To decide if a number is positive/negative/neutral, we could also start off by asking if the number is equal to zero, like in this flowchart:
Translated into JavaScript, that flow looks like this:
var numberSign;
if (number === 0) {
numberSign = "neutral";
} else {
if (number > 0) {
numberSign = "positive";
} else {
numberSign = "negative";
}
}
This flow is just as correct as the other flow and will output the same set of values for inputs as the first flow.
In fact, there are at least four more possible flows to achieve the same result.
Which flow should your program follow? As long as each of them achieve the same result, go for the flow that seems the most natural and intuitive. Once you've programmed the flow, always test your program with a range of values to make sure it works as expected.
Deeper nesting
It would be neat if everything in the world divided neatly into three categories, but the world's a messier place than that.
Fortunately, we can nest conditionals as many levels as needed and our program can go down many different paths.
For example, we could write a program to classify a salsa into mild, medium, hot, or extreme, based on the Scoville rating of its peppers.
This flowchart describes the desired logic:
We can implement that in JavaScript with
if
/else
statements like before, but with one additional level of nesting.var level;
if (rating < 5000) {
level = "mild";
} else {
if (rating < 20000) {
level = "medium";
} else {
if (rating < 70000) {
level = "hot";
} else {
level = "extreme";
}
}
}
Now our program can assign
level
to one of four different values, depending on what path is selected. We need to be more careful about the ordering here, since each nested
if
assumes the program already checked the previous condition. We can't mix up the conditions as much as we could for the positive/negative/neutral program. Once again, always think carefully through your ordering when you're structuring your conditionals.✏️ The program below is a simple daily calorie calculator for cats and dogs. Try changing the top variables to reflect your own pet, if you have one, or a friend's pet. You can also make the calculator more accurate by incorporating factors like whether your pet is overweight or indoor/outdoor. With nested conditionals, you can check anything!
Chained conditionals
When we're programming, we often find ourselves using conditionals to check possible values of a single variable.
We've seen two examples of that already, and we can summarize each in a table:
condition | output |
---|---|
number > 0 | "positive" |
number < 0 | "negative" |
number === 0 | "neutral" |
condition | output |
---|---|
rating < 5000 | "mild" |
rating < 20000 | "medium" |
rating < 70000 | "hot" |
rating >= 70000 | "extreme" |
Many programming languages include a way to write "chained" conditionals that are an even better way to check these values.
In the JavaScript language, we can chain conditionals using
else if
statements. Here's how we can write the number sign checker with chained conditionals:
var numberSign;
if (number > 0) {
numberSign = "positive";
} else if (number < 0) {
numberSign = "negative";
} else {
numberSign = "neutral";
}
This code is very similar to the original code, but uses an
else if
instead of a nested else
with an if
inside it. A chained conditional is generally easier to read, especially as the number of conditions increases, and often a bit shorter.
Here's the salsa level calculator written with chained conditionals:
var level;
if (rating < 5000) {
level = "mild";
} else if (rating < 20000) {
level = "medium";
} else if (rating < 70000) {
level = "hot";
} else {
level = "extreme";
}
Compare that to the original version with nested conditionals. Flows much better, doesn't it?
Not all languages provide the ability to chain conditionals, but if you are programming in a language like JS or Python that does include the feature, do take advantage of it for cases like these.
📝 Exam Tip: The AP CSP exam does not include chained conditionals. It uses nested conditionals in all situations.
Nested conditionals in pseudocode
This pseudocode shows a simple nested conditional, with one outer
IF
/ELSE
and one inner IF
/ELSE
:IF (<condition 1>)
{
<instructions 1>
}
ELSE
{
IF (<condition 2>)
{
<instructions 2>
}
ELSE
{
<instructions 3>
}
}
Here's the sign checking program in pseudocode:
IF (number > 0)
{
numberSign ← "positive";
}
ELSE
{
IF (number < 0)
{
numberSign ← "negative";
}
ELSE
{
numberSign ← "neutral";
}
}
🙋🏽🙋🏻♀️🙋🏿♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!
Want to join the conversation?
- what is the difference between chain and nested conditionals ''at, 9:05(3 votes)
- In Javascript a chain uses "else if" to chain conditionals together, rather than nesting "if" statements within "else" statements. In Python a chained conditional uses "elif".(5 votes)
- me the only one here(3 votes)
- In the pet calorie example, one of the coded lines was: "
if (isNeutered) {
println(1.6 * restingEnergyReq);
} else {
println(1.8 * restingEnergyReq);"
How would you write the code if you wanted it to be true when the dog is NOT neutered?(0 votes)- From the author:In JavaScript, you can either do if(isNeutered === false) [as KING showed in their reply] or if(!isNeutered). You can also switch the if/else, since the else is what's executed when the if condition is false.(4 votes)
- Im pretty confused on what else if means for chained conditionals? I understand what else and if are.(1 vote)
- Suppose we have some generic code as follows.
'
if(A){...}
else if(B){...}
else{...}
'
The program will first check if A is true. If it is true, then the program will run the subsequent block of code and that will be it. However, the program will only check if B is true (and possibly run its subsequent code) if A happens to be false. Finally, the program will execute the code after the else statement only when both A and B are false.(1 vote)
- Are there chained conditionals for pseudocode?(1 vote)
- The exam reference sheet currently in use (2020 version) does not mention else-if statements, so you most likely don't need to know it.(0 votes)
- Thank you for providing this information for us all to learn. I am unclear how you are deciding when and where to "close" off a statement with "{" and "} with if/else statements after the first "if" and "else". Could you please provide some clarity?(0 votes)
- All if-else structures in the code will follow the same structure, i.e.
if(condition) {
do something...
}
else {
do something else...
}
The above structure can become confusing when we deal with nested conditionals. However, you can remember the general syntactic structure of an if-else statement: if (condition) {} else {}. Therefore, you haveif (condition)
followed by one opening'{'
and one closing'}'
. Afterward, you haveelse
followed by one opening'{'
and one closing'}'
. Regardless of nesting or the bodies of the if statements, this structure remains consistent.
Let us try to follow this structure in code:if (condition) { // opening '{' (1st if)
do something...
} // closing '}' (1st if)
else { // opening '{' (1st else)
if (condition) { // opening '{' (2nd if)
do something...
} // closing '}' (2nd if)
else { // opening '{' (2nd else)
do something else...
} // closing '}' (2nd else)
} // closing '}' (1st else)
The code above is a tad messy because it can be difficult to code in the context of a comment, but if you parse through it and take time to understand it you will observe the aforementioned repetitive structure. Once you get a handle on this structure, nested if-else statements will become natural to you. Also, do note that an "else" is not strictly necessary with each if statement, but I have always include an else to better match your specific question.(1 vote)
- For the first negative, positive, neutral sign example, would one have to define "number" as a variable prior to running the rest of the code?(0 votes)
- Yes number would have to be defined. In this case it would most likely be part of the functions signature, so the number would the input the function takes in.(0 votes)
- there seems to always be a final } at the end, is that required? I thought I saw 2 }} at the end on another screen how are they used. For example:
IF
{instruction}
else
{instruction}
}(0 votes)- If you are nesting conditionals, you need to have curly braces around the code nested inside the nested conditional.
Such as:IF (condition)
{
IF (condition)
{
<block of statements>
}
ELSE
{
<block of statements>
}
}
Basically, each conditional needs a pair of curly braces, like how you can see in some of the examples in the article. For the example that you gave in your question, the firstIF
would need a '{' after it to pair with the closing '}' at the end of that code.(0 votes)