If…Then

The If…Then structure is a conditional statement, or sometimes referred to as a decision structure. It is used to perform a section of code if and only if the condition is true. The condition is checked by using a Boolean statement. If the condition is not true (meaning false), then the section of code is not performed, it is just passed over. The form of an If…Then statement is:

IF (Boolean expression) THEN
statements to be performed …
ENDIF

The indentation (usually 2 or 4 spaces, NOT A TAB, except for languages like Go!), used in the If…Then statement is a coding convention used in almost every language. It is there to make the statement easier to read. It has no effect on how the code works (except in languages like python), and could be ignored; however, it is REALLY BAD programming style not to have them. You will also notice that some programming languages like to place the Boolean expression in brackets, while others do not. It is just style, but you should follow the language’s conventions.

Here is a problem that can be solved using an If…Then statement. I have a class that can only hold 30 students because that is how many chairs I have. Ask the user to enter a number of students and tell me if I have too many students for the number of chairs I have.

The top-down design will have decision logic in it. You do not use a diamond in a top-down design, you still only use rectangles. Here is what a top-down design might look like for this problem:

Top-Down Design for If…Then statement

Top-Down Design for If…Then statement

Remember from the section on flowcharts, the diamond shape represented decisions. The If…Then statement is the translation of a decision in a flowchart to code. Note that you MUST mark the, “Yes”, and, “No”, path, so that people can follow the flow of logic. The above examples would look like the following in a flowchart:

Flowchart for If…Then statement

If…Then flowchart

You will also be using If…Then statements in pseudocode. The above problem looks like this in pseudocode. Note that you do indent when you are inside an If…Then statement in pseudocode. Also note that “IF”, “THEN” and “ENDIF” are all bold and CAPS:

Pseudocode for If…Then statement

GET number_of_students
IF (number_of_students > 30) THEN
SHOW “Too many students!”
ENDIF

In the code examples below, if the variable numberOfStudents (or number_of_students), happens to be a number that is greater than 30 (say 32), the next line of code is performed. If the variable is not greater than 30 (say it is exactly 30), then the next line of code is skipped over and NOT performed. Note that the number of chairs does not change often in my room, so I will use a constant to hold that value.

Code for If…Then 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
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks if there is over 30 students

#include <stdio.h>

int main() {
    // this function checks if there is over 30 students
    const int MAX_STUDENT_NUMBER = 30;
    int numberOfStudents;

    // input
    printf("Enter the number of students: ");
    scanf("%d", &numberOfStudents);

    // process
    if (numberOfStudents > MAX_STUDENT_NUMBER) {
        // output
        printf("Too many students!\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
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks if there is over 30 students

#include <iostream>

int main() {
    // this function checks if there is over 30 students
    const int MAX_STUDENT_NUMBER = 30;
    int numberOfStudents;

    // input
    std::cout << "Enter the number of students: ";
    std::cin >> numberOfStudents;

    // process
    if (numberOfStudents > MAX_STUDENT_NUMBER) {
        // output
        std::cout << "Too many students!\n";
    }

    std::cout << "\nDone." << std::endl;
}
 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
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks if there is over 30 students
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function checks if there is over 30 students
        const int MAX_STUDENT_NUMBER = 30;
        int numberOfStudents;

        // input
        Console.Write("Enter the number of students: ");
        numberOfStudents = Convert.ToInt32(Console.ReadLine());

        // process
        if (numberOfStudents > MAX_STUDENT_NUMBER) {
            // output
            Console.WriteLine("Too many students!");
        }

        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
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks if there is over 30 students
 */

package main

import "fmt"

func main() {
	// this function checks if there is over 30 students
	const maxStudentNumber int = 30
	var numberOfStudents int

	// input
	fmt.Print("Enter the number of students: ")
	fmt.Scan(&numberOfStudents)

	// process
	if numberOfStudents > maxStudentNumber {
		// output
		fmt.Println("Too many students!")
	}

	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
/*
 * This program checks if there is over 30 students
 *
 * @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 checks if there is over 30 students
    final int MAX_STUDENT_NUMBER = 30;
    int numberOfStudents;

    // input
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of students: ");
    numberOfStudents = input.nextInt();

    // process
    if (numberOfStudents > MAX_STUDENT_NUMBER) {
      // output
      System.out.println("Too many students!");
    }

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks if ther is over 30 students
*/

const prompt = require('prompt-sync')()
const MAX_STUDENT_NUMBER = 30

// input
const numberOfStudents = parseInt(prompt('Enter the number of students: '))

// process
if (numberOfStudents > MAX_STUDENT_NUMBER) {
    // output
    console.log("Too many students!")
}

console.log("\nDone.")

constants.py

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module holds constants
"""

# constant definition
MAX_STUDENT_NUMBER = 30

main.py

 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
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module shows checks if over 30 students
"""


from constants import MAX_STUDENT_NUMBER


def main() -> None:
    """The main() function checks if over 30 students, returns None."""

    # input
    number_of_students = int(input("Enter the number of students: "))

    # process
    if number_of_students > MAX_STUDENT_NUMBER:
        # output
        print("Too many students!")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output