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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a nested if statement

#include <stdio.h>

int main() {
    // this function uses a nested if statement
    int cookiesSold;

    // input
    printf("Enter the number of boxes of cookies you sold: ");
    scanf("%d", &cookiesSold);
    printf("\n");

    // process & output
    if (cookiesSold >= 20) {
        if (cookiesSold < 30) {
            printf("You get a small prize.\n");
        } else {
            printf("You get a large prize.\n");
        }
    } else {
        printf("No prize.\n");
    }

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a nested if statement

#include <iostream>

int main() {
    // this function uses a nested if statement
    int cookiesSold;

    // input
    std::cout << "Enter the number of boxes of cookies you sold: ";
    std::cin >> cookiesSold;
    std::cout << std::endl;

    // process & output
    if (cookiesSold >= 20) {
        if (cookiesSold < 30) {
            std::cout << "You get a small prize." << std::endl;
        } else {
            std::cout << "You get a large prize." << std::endl;
        }
    } else {
        std::cout << "No prize." << std::endl;
    }

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested if statement
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function uses a nested if statement

        int cookiesSold;

        // input
        Console.Write("Enter the number of boxes of cookies you sold: ");
        cookiesSold = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine();

        // process & output
        if (cookiesSold >= 20) {
            if (cookiesSold < 30) {
                Console.WriteLine("You get a small prize.");
            } else {
                Console.WriteLine("You get a large prize.");
            }
        } else {
            Console.WriteLine("No prize.");
        }

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested if statement
 */

package main

import (
	"fmt"
)

func main() {
	// this function uses a nested if statement

	var cookiesSold int

	// input
	fmt.Print("Enter the number of boxes of cookies you sold: ")
	fmt.Scan(&cookiesSold)
	fmt.Println()

	// process & output
	if cookiesSold >= 20 {
		if cookiesSold < 30 {
			fmt.Println("You get a small prize.")
		} else {
			fmt.Println("You get a large prize.")
		}
	} else {
		fmt.Println("No prize.")
	}

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 * This program uses a nested if statement
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // this function uses a nested if statement

    // create Scanner object for user input
    Scanner scanner = new Scanner(System.in);

    // input
    System.out.print("Enter the number of boxes of cookies you sold: ");
    String cookiesSoldStr = scanner.nextLine();
    System.out.println();

    // process & output
    int cookiesSold = Integer.parseInt(cookiesSoldStr);

    if (cookiesSold >= 20) {
      if (cookiesSold < 30) {
        System.out.println("You get a small prize.");
      } else {
        System.out.println("You get a large prize.");
      }
    } else {
      System.out.println("No prize.");
    }

    // close the Scanner object
    scanner.close();
    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested if statement
 */

const prompt = require("prompt-sync")()

// input
const cookiesSoldStr = prompt("Enter the number of boxes of cookies you sold: ")
console.log("")

// process & output
const cookiesSold = parseInt(cookiesSoldStr)

if (cookiesSold >= 20) {
  if (cookiesSold < 30) {
    console.log("You get a small prize.")
  } else {
    console.log("You get a large prize.")
  }
} else {
  console.log("No prize.")
}

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses a nested if statement
"""


def main() -> None:
    """The main() function uses a nested if statement, returns None."""

    # input
    cookies_sold = int(input("Enter the number of boxes of cookies you sold: "))
    print("")

    # process & output
    if cookies_sold >= 20:
        if cookies_sold < 30:
            print("You get a small prize.")
        else:
            print("You get a large prize.")
    else:
        print("No prize.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output