Nested If Statements
Sometimes a single if statement, even a long If…Then…ElseIf…ElseIf…Else is not a suitable structure to model your problem. Sometimes after one decision is made, there is another second decision that must follow. In these cases, if statements can be nested within if statements (or other structures as we will see later).
The nested if statements (in most computer programming languages), takes the generic form of:
IF (Boolean expression A) THEN
statement(s)
IF (Boolean expression B) THEN
statement(s)
ELSE
Alternate statements to be performed
ENDIF
ELSE
Alternate statements to be performed
ENDIF
In this example problem a school is going to sell cookies to raise money. If a student sells 20 or more boxes, they get a prize. If they sell less than 30, they get a, “small” prize. If they sell more than 30, they get a, “large” prize. (Yes you could use an If…Then…ElseIf… statement.)
Top-Down Design for Nested If statement
Flowchart for Nested If statement
Pseudocode for Nested If statement
GET cookies_sold
IF (cookies_sold >= 20) THEN
IF (cookies_sold < 30) THEN
SHOW “Small prize!”
ELSE
SHOW “Large prize!”
ENDIF
ELSE
SHOW “No prize.”
ENDIF