Return Values

If this was math class, the definition of a mathimatical function might be, “… a function is a relation between sets that associates to every element of a first set exactly one element of the second set,” which is a fancy way to say that if you put in a particular number into the function you get one and only one number out and it will always be the same value. The key is that you actually get something back. In computer science it is also common for functions to give you something back and we normally call this a return value or statement.

We have already seen many built in functions that have a return value, like the square root function:

Code for Function with a Return Value

// square root function
someVariable = sqrt(someNumber);
// square root function
someVariable = sqrt(someNumber);
// square root function
someVariable = sqrt(someNumber);
// square root function
someVariable = math.Sqrt(someNumber);
// square root function
someVariable = sqrt(someNumber);
// square root function
someVariable = sqrt(someNumber);
# square root function
some_variable = math.sqrt(some_number)

You will notice that the function is now on the right hand side of an assignment statement and the calculated value is being placed right into another variable. To allow this ability, we normally use the reserved word “return” to pass the value back. In many programming languages, in the definition of the function you must specify what type of variable will be returned. This way the IDE can confirm that the same types are being passed back and placed into a variable of the same type. This way the language remains type safe.

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

    // process
    float area = M_PI * radius ** 2;

    return area;
}
float calculateArea(int radius) {
    // this function calculates the area of circle

    // process
    float area = M_PI * radius ** 2;

    return area;
}
    static float calculateArea(int radius) {
        // this function calculates the area of circle

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

        return area;
    }
 func calculateArea(radius int) {
	 // this function calculates the area of circle
 
	 // process
	 area := math.Pi * radius ** 2
 
	return area
 }
  /**
   * Calculates calculates the area of circle.
   *
   * @param args nothing passed in
   */
  public static float calculateArea(int radius) {
    // process
    float area = Math.PI * Math.pow(radius, 2);

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

  return area
}

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

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

    return area

Now that we know how to use a return statement, we should no longer print out results inside a function like in the last few chapters. It is much better style to retrun the value from a function and let the calling process decide what to do with it. Here is the example from last section, this time using return values:

 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
// 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>

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

    // process
    float area = M_PI * radius ** 2;

    return area;
}

int main() {
    int radius;
    float area = 0.0;

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

    // call functions
    area = calculateArea(radius);

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

    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
// 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>


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

    // process
    float area = M_PI * radius ** 2;

    return area;
}

int main() {
    int radius = 0;
    float area = 0.0;

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

    // call functions
    area = calculateArea(radius);

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

    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
36
37
38
39
/* 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 float calculateArea(int radius) {
        // this function calculates the area of circle

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

        return area;
    }
 
    public static void Main (string[] args) {
        int radius;
        float area = 0.0;

        // input
        Console.Write("Enter the radius of a circle (cm): ");
        radius = int.Parse(Console.ReadLine());
        Console.WriteLine("");

        // call functions
        area = calculateArea(length, width);

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

        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
/**
 * 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
 
	return area
 }
 
 func main() {
	var radius int
	var area float

	 // input
	 fmt.Print("Enter the radius of a circle (cm): ")
	 fmt.Scanln(&radius)
	 fmt.Println()
 
	 // call functions
	 area = calculateArea(radius)

	 // output
	 fmt.Printf("The area is %d cm²\n", area)
 
	 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
/*
 * 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 float calculateArea(int radius) {
    // process
    float area = Math.PI * Math.pow(radius, 2);

    return 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 float main(final String[] args) {
    int radius;
    float area = 0.0;

    // input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the radius of a circle (cm): ");
    radius = scanner.nextInt();
    System.out.println();

    // call functions
    area = calculateArea(radius);

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

    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
/**
 * 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;

  return area
}

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

// call functions
area = calculateArea(radius);

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

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
36
37
#!/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) -> float:
    """The calculate_area() function calculates the area of circle, returns float."""

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

    return area


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
    area = calculate_area(radius)

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

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output