Functions with a Parameter

A function often needs pieces of information to be able to complete its work. In the last section you might have noticed that I had to ask for the length and width twice, once for each of the area and perimeter calculations; clearly not ideal. One method of doing this is to declare the variable as a global variable and then any code within that file can access it. This is a very brute force method and is very bad programming style. By doing it this way, the variable is created and held in memory for the entire time the file is running, even though the information may only be needed for a small fraction of the time. Also the function is no longer portable, since it relies on external global variables that might not exist in another program. A better, more elegant and more memory friendly way is to pass the information into the function using a parameter. There are three main ways to pass information to a function, by value, by reference and by object reference. For the time being we will just consider by value. (We will even assume python is doing by value, even though it is really doing it by object reference.)

Passing By Value

The first method of transferring information to a function is to pass it, “By Value”. This means that a copy of the data is made and it is passed over to the function to do with it what it pleases. Since it is a copy of the data, any changes to the data are not reflected in the original variable. From the animation below you can see that when the cup is passed “By Value” to the function and then filled up, the original cup is still empty. This is because the variable passed to the function is a copy, not the original variable. If the function changes this variable, nothing happens to the original one.

Pass by value or reference

A variable or value passed along inside a function call is called an parameter. Parameter(s) are usually placed inside a bracket when you invoke the function. For example:

Code for Function with a Parameter

    calculateArea(radius);
    calculateArea(radius);
        calculateArea(radius);
	calculateArea(radius)
    calculateArea(radius);
calculateArea(radius);
    # call functions

When you are creating your function, you must also tell the program that the function is expecting these two values. To do this after the function name declaration you place in brackets the two declaration statements declaring that the function must be passed in two variables (just like when a regular variable is being declared). If your programming language requires that you declare what type the variables will be normally, you will most like have to do that too.

The following is the function declaration line for the examples above:

void calculateArea(int radius) {
void calculateArea(int radius) {
    static void calculateArea(int radius) {
func calculateArea(radius int) {
  public static void calculateArea(int radius) {
function calculateArea(radius) {

Here is a full example of the previous sections program, but now the main function takes care of getting the radius. This way it only has to ask you the information once and it passes the radius to the 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
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program calculates the area of circle

#include <stdio.h>
#include <math.h>

void calculateArea(int radius) {
    // this function calculates the area of circle

    // process
    int area = M_PI * radius * pow( 2, 2);

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

int main() {
    // input
    printf("Enter the radius of a circle (cm): ");
    int radius;
    scanf("%d", &radius);
    printf("\n");

    // call functions
    calculateArea(radius);

    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
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program calculates the area of circle

#include <iostream>
#include <cmath>


void calculateArea(int radius) {
    // this function calculates the area of circle

    // process
    int area = area = M_PI * radius * pow(radius, 2);

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

int main() {
    int radius;
    
    // input
    std::cout << "Enter the radius of a circle (cm): ";
    std::cin >> radius;
    std::cout << std::endl;

    // call functions
    calculateArea(radius);

    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
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program calculates the area of circle
*/

using System;

/*
 * The Program class
 * Contains all methods for performing basic variable usage
*/
class Program {
    static void calculateArea(int radius) {
        // this function calculates the area of circle

        // process
        int area = Math.Pi * radius ** 2;

        // output
        Console.WriteLine($"The area is {area} cm²");
    }
 
    public static void Main (string[] args) {
        // input
        Console.Write("Enter the radius of a circle (cm): ");
        int radius = int.Parse(Console.ReadLine());
        Console.WriteLine("");

        // call functions
        calculateArea(radius);

        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 calculates the area of circle
 */

package main

import (
	"fmt"
	"math"
)

func calculateArea(radius int) {
	// this function calculates the area of circle

	// process
	area := math.Pi * radius ** 2

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

func main() {
	// input
	var radius int
	fmt.Print("Enter the radius of a circle (cm): ")
	fmt.Scanln(&radius)
	fmt.Println()

	// call functions
	calculateArea(radius)

	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
/*
 * This program calculates the area of circle
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

final class Main {
  /**
   * Calculates calculates the area of circle.
   *
   * @param args nothing passed in
   */
  public static void calculateArea(int radius) {
    // process
    int area = Math.PI * Math.pow(radius, 2);

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

  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) {
    // input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the radius of a circle (cm): ");
    int radius = scanner.nextInt();
    System.out.println();

    // call functions
    calculateArea(radius);

    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
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program calculates the area of circle
 */

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

function calculateArea(radius) {
  // this function calculates the area of circle
  
  // process
  const area = Math.PI * radius ** 2;

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

// input
const radius = parseInt(prompt("Enter the radius of a circle (cm): "));
console.log();

// call functions
calculateArea(radius);

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
30
31
32
33
34
35
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module calculates the area of circle
"""

import math


def calculate_area(radius: int) -> None:
    """The calculate_area() function calculates the area of circle, returns None."""

    # process
    area = math.pi * radius ** 2

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


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

    # input
    radius = int(input("Enter the radius of a circle (cm): "))
    print("")

    # call functions
    calculate_area(radius)

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output