Understanding Functions

A Subroutine or what we will just refer to as a function is a block of code written to perform a specific task. We have actually been using functions all along our programming journey so far and you probably have not even noticed. Many functions are built into most programming languages, like the print() function for example. In python we usually place our code in main(), which is a function. In C, C++ or Java the compiler looks for the main() function to start running the program. You can also create functions to do specific calculations, like converting temperature from Celsius to Fahrenheit for example. This type of conversion is very common and we might want to use it in another program (re-usability is very important in programming; why re-invent the wheel, just use someone else’s code, as long as you can trust that it will work!).

Functions need to have two (2) seperate mechanisms to work correctly. You need a way to create the function in your program and you also need a way to then “call” the function and get the code inside of it to run. Although not normally needed for the computer, we usually place the function definition before we call the function, so that when people are actually reading the code they have seen the function definition and know what it will do before they see it being called.

This is a good template for keeping all the parts of your program organized in a program file:

  1. comment header

  2. global (to the file) constant(s)

  3. global (to the file) variable(s)

  4. function(s)

  5. main body of code

Creating and Calling a Function

Each programming language has its own syntax to create and call a function. Here is an example program that uses functions to calculate area and perimeter (I know there are many ways to improve this code, we will be doing that in the next sections)

Code for Creating and Calling a Function

 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
41
42
43
44
45
46
47
48
49
50
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses user defined functions

#include <stdio.h>

void calculateArea()
{
    // input
    printf("Enter the length of a rectangle (cm): ");
    int length;
    scanf("%d", &length);
    printf("Enter the width of a rectangle (cm): ");
    int width;
    scanf("%d", &width);

    // process
    int area = length * width;

    // output
    printf("The area is %d cm²\n\n", area);
}

void calculatePerimeter()
{
    // input
    printf("Enter the length of a rectangle (cm): ");
    int length;
    scanf("%d", &length);
    printf("Enter the width of a rectangle (cm): ");
    int width;
    scanf("%d", &width);

    // process
    int perimeter = 2 * (length + width);

    // output
    printf("The perimeter is %d cm\n\n", perimeter);
}

int main() {
    // call functions
    calculateArea();
    calculatePerimeter();

    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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses user defined functions

#include <iostream>

void calculateArea() {
    // input
    std::cout << "Enter the length of a rectangle (cm): ";
    int length;
    std::cin >> length;
    std::cout << "Enter the width of a rectangle (cm): ";
    int width;
    std::cin >> width;

    // process
    int area = length * width;

    // output
    std::cout << "The area is " << area << " cm²\n\n";
}

void calculatePerimeter() {
    // input
    std::cout << "Enter the length of a rectangle (cm): ";
    int length;
    std::cin >> length;
    std::cout << "Enter the width of a rectangle (cm): ";
    int width;
    std::cin >> width;

    // process
    int perimeter = 2 * (length + width);

    // output
    std::cout << "The perimeter is " << perimeter << " cm\n\n";
}

int main() {
    // call functions
    calculateArea();
    calculatePerimeter();

    std::cout << "Done." << 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
36
37
38
39
40
41
42
43
44
45
46
47
48
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses user defined functions
*/

using System;

/*
 * The Program class
 * Contains all methods for performing basic variable usage
*/
class Program {
    static void calculateArea() {
        // input
        Console.Write("Enter the length of a rectangle (cm): ");
        int length = int.Parse(Console.ReadLine());
        Console.Write("Enter the width of a rectangle (cm): ");
        int width = int.Parse(Console.ReadLine());

        // process
        int area = length * width;

        // output
        Console.WriteLine($"The area is {area} cm²\n");
    }

    static void calculatePerimeter() {
        // input
        Console.Write("Enter the length of a rectangle (cm): ");
        int length = int.Parse(Console.ReadLine());
        Console.Write("Enter the width of a rectangle (cm): ");
        int width = int.Parse(Console.ReadLine());

        // process
        int perimeter = 2 * (length + width);

        // output
        Console.WriteLine($"The perimeter is {perimeter} cm\n");
    }

    public static void Main (string[] args) {
        // call functions
        calculateArea();
        calculatePerimeter();

        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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses user defined functions
 */

package main

import (
	"fmt"
)

func calculateArea() {
	// input
	var length, width int
	fmt.Print("Enter the length of a rectangle (cm): ")
	fmt.Scanln(&length)
	fmt.Print("Enter the width of a rectangle (cm): ")
	fmt.Scanln(&width)

	// process
	area := length * width

	// output
	fmt.Printf("The area is %d cm²\n\n", area)
}

func calculatePerimeter() {
	// input
	var length, width int
	fmt.Print("Enter the length of a rectangle (cm): ")
	fmt.Scanln(&length)
	fmt.Print("Enter the width of a rectangle (cm): ")
	fmt.Scanln(&width)

	// process
	perimeter := 2 * (length + width)

	// output
	fmt.Printf("The perimeter is %d cm\n\n", perimeter)
}

func main() {
	// call functions
	calculateArea()
	calculatePerimeter()

	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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * This program uses user defined functions
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

final class Main {
  /**
   * Calculates area of rectangle.
   *
   * @param args nothing passed in
   */
  public static void calculateArea() {
    // input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the length of a rectangle (cm): ");
    int length = scanner.nextInt();
    System.out.print("Enter the width of a rectangle (cm): ");
    int width = scanner.nextInt();

    // process
    int area = length * width;

    // output
    System.out.printf("The area is %d cm²%n%n", area);
  }

  /**
   * Calculates perimeter of rectangle.
   *
   * @param args nothing passed in
   */
  public static void calculatePerimeter() {
    // input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the length of a rectangle (cm): ");
    int length = scanner.nextInt();
    System.out.print("Enter the width of a rectangle (cm): ");
    int width = scanner.nextInt();

    // process
    int perimeter = 2 * (length + width);

    // output
    System.out.printf("The perimeter is %d cm%n%n", perimeter);
  }

  private Main() {
    // Prevent instantiation
    // Optional: throw an exception e.g. AssertionError
    // if this ever *is* called
    throw new IllegalStateException("Cannot be instantiated");
  }

  /**
   * Main entry point into program.
   *
   * @param args nothing passed in
   */
  public static void main(final String[] args) {
    // call functions
    calculateArea();
    calculatePerimeter();

    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
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses user defined functions
 */

const prompt = require('prompt-sync')();

function calculateArea() {
  // input
  const length = parseInt(prompt("Enter the length of a rectangle (cm): "));
  const width = parseInt(prompt("Enter the width of a rectangle (cm): "));

  // process
  const area = length * width;

  // output
  console.log(`The area is ${area} cm²\n`);
}

function calculatePerimeter() {
  // input
  const length = parseInt(prompt("Enter the length of a rectangle (cm): "));
  const width = parseInt(prompt("Enter the width of a rectangle (cm): "));

  // process
  const perimeter = 2 * (length + width);

  // output
  console.log(`The perimeter is ${perimeter} cm\n`);
}

// call functions
calculateArea();
calculatePerimeter();

console.log("Done.");
 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
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses user defined functions
"""


def calculate_area() -> None:
    """The calculate_area() function calculates area of a rectangle, returns None."""

    # input
    length = int(input("Enter the length of a rectangle (cm): "))
    width = int(input("Enter the width of a rectangle (cm): "))

    # process
    area = length * width

    # output
    print(f"The area is {area} cm²")
    print("")


def calculate_perimeter() -> None:
    """The calculate_perimeter() function calculates perimeter of a rectangle, returns None."""

    # input
    length = int(input("Enter the length of a rectangle (cm): "))
    width = int(input("Enter the width of a rectangle (cm): "))

    # process
    perimeter = 2 * (length + width)

    # output
    print(f"The perimeter is {perimeter} cm")
    print("")


def main() -> None:
    """The main() function just calls other functions, returns None."""

    # call functions
    calculate_area()
    calculate_perimeter()

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output