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

Top-Down Design for Nested If statement

Flowchart for Nested If statement

Nested If flowchart

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

Code for Nested If statement

 1// Copyright (c) 2020 Mr. Coxall All rights reserved.
 2//
 3// Created by: Mr. Coxall
 4// Created on: Sep 2020
 5// This program uses a nested if statement
 6
 7#include <stdio.h>
 8
 9int main() {
10    // this function uses a nested if statement
11    int cookiesSold;
12
13    // input
14    printf("Enter the number of boxes of cookies you sold: ");
15    scanf("%d", &cookiesSold);
16    printf("\n");
17
18    // process & output
19    if (cookiesSold >= 20) {
20        if (cookiesSold < 30) {
21            printf("You get a small prize.\n");
22        } else {
23            printf("You get a large prize.\n");
24        }
25    } else {
26        printf("No prize.\n");
27    }
28
29    printf("\nDone.\n");
30    return 0;
31}

Example Output

Code example output