Functions with Multiple Parameters
All of the functions that we have looked at to this point, there has been one (1) parameter passed into the function. This is not always the case. There might be cases where you need to pass in two (2) or more peices of infomation. Suppose you have a function that calculates the area of a rectangle. In this case unless you are only going to do squares, you will need a length and a width.
Fortunately you can pass multiple parameters into a function. The thing to remember is that, since you now have more than one (1) item, the order of the parameters is important, since this is how the computer is going to keep track of the different variables.
Since people are not always great at keeping things in order, many programming languages (but not all) let you pass multiple parameters to functions using “parameteres by keyword”. This means that you actually give each parameter a name and then refer to this name when you are passing the values to the function, so there is no confusion about what value is going where.
In the example below, I have a function that can calculate the area of a rectangle. Is is important to keep all two (2) parameters organzied, or you will not get the correct answer. To do this each parameter will use named parameters (if possible):
Code for Function with Multiple Parameters
1// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program calculates the area of a rectangle
6
7#include <stdio.h>
8
9int calculateArea(int length, int width) {
10 // this function calculates the area of a rectangle
11
12 // process
13 int area = length * width;
14
15 return area;
16}
17
18int main() {
19 // this function does the input and output
20 int area = 0;
21
22 // input
23 printf("Enter the length of a rectangle (cm): ");
24 int lengthFromUser;
25 scanf("%d", &lengthFromUser);
26 printf("Enter the width of a rectangle (cm): ");
27 int widthFromUser;
28 scanf("%d", &widthFromUser);
29 printf("\n");
30
31 // call functions
32 area = calculateArea(lengthFromUser, widthFromUser);
33
34 // output
35 printf("The area is %d cm²\n", area);
36
37 printf("\nDone.\n");
38 return 0;
39}
1// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program calculates the area of a rectangle
6
7#include <iostream>
8
9
10int calculateArea(int length, int width) {
11 // this function calculates the area of a rectangle
12
13 // process
14 int area = length * width;
15
16 return area;
17}
18
19int main() {
20 // this function does the input and output
21 int area = 0;
22 int perimeter = 0;
23
24 // input
25 std::cout << "Enter the length of a rectangle (cm): ";
26 int lengthFromUser;
27 std::cin >> lengthFromUser;
28 std::cout << "Enter the width of a rectangle (cm): ";
29 int widthFromUser;
30 std::cin >> widthFromUser;
31 std::cout << std::endl;
32
33 // call functions
34 area = calculateArea(lengthFromUser, widthFromUser);
35
36 // output
37 std::cout << "The area is " << area << " cm²\n";
38
39 std::cout << "\nDone." << std::endl;
40 return 0;
41}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program calculates the area of a rectangle
4*/
5
6using System;
7
8/*
9 * The Program class
10 * Contains all methods for performing basic variable usage
11*/
12class Program {
13 static int calculateArea(int length, int width) {
14 // this function calculates the area of a rectangle
15
16 // process
17 int area = length * width;
18
19 return area;
20 }
21
22 public static void Main (string[] args) {
23 // this function does the input and output
24 int area = 0;
25
26 // input
27 Console.Write("Enter the length of a rectangle (cm): ");
28 int lengthFromUser = int.Parse(Console.ReadLine());
29 Console.Write("Enter the width of a rectangle (cm): ");
30 int widthFromUser = int.Parse(Console.ReadLine());
31 Console.WriteLine("");
32
33 // call functions
34 area = calculateArea(width: widthFromUser, length: lengthFromUser);
35
36 // output
37 Console.WriteLine($"The area is {area} cm²");
38
39 Console.WriteLine("\nDone.");
40 }
41}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program uses user defined functions
5 */
6
7 package main
8
9 import (
10 "fmt"
11 )
12
13 func calculateArea(length int, width int) {
14 // this function calculates the area of a rectangle
15
16 // process
17 area := length * width
18
19 return area
20 }
21
22 func main() {
23 // this function does the input and output
24 var area = 0
25
26 // input
27 var length_from_user, width_from_user int
28 fmt.Print("Enter the length of a rectangle (cm): ")
29 fmt.Scanln(&length_from_user)
30 fmt.Print("Enter the width of a rectangle (cm): ")
31 fmt.Scanln(&width_from_user)
32 fmt.Println()
33
34 // call functions
35 area = calculateArea(length_from_user, width_from_user)
36
37 // output
38 fmt.Printf("The area is %d cm²\n", area)
39
40 fmt.Println("\nDone.")
41 }
42
1/*
2 * This program calculates area of rectangle
3 *
4 * @author Mr Coxall
5 * @version 1.0
6 * @since 2020-09-01
7 */
8
9import java.util.Scanner;
10
11final class Main {
12 /**
13 * Calculates area of rectangle.
14 *
15 * @param args nothing passed in
16 */
17 public static int calculateArea(int length, int width) {
18 // process
19 int area = length * width;
20
21 return area;
22 }
23
24 private Main() {
25 // Prevent instantiation
26 // Optional: throw an exception e.g. AssertionError
27 // if this ever *is* called
28 throw new IllegalStateException("Cannot be instantiated");
29 }
30
31 /**
32 * Main entry point into program.
33 *
34 * @param args nothing passed in
35 */
36 public static void main(final String[] args) {
37 // this function does the input and output
38 int area = 0;
39
40 // input
41 Scanner scanner = new Scanner(System.in);
42 System.out.print("Enter the length of a rectangle (cm): ");
43 int lengthFromUser = scanner.nextInt();
44 System.out.print("Enter the width of a rectangle (cm): ");
45 int widthFromUser = scanner.nextInt();
46 System.out.println();
47
48 // call functions
49 area = calculateArea(lengthFromUser, widthFromUser);
50
51 // output
52 System.out.printf("The area is %d cm²%n", area);
53
54 System.out.println("\nDone.");
55 }
56}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program calculates the area of a rectangle
5 */
6
7const prompt = require('prompt-sync')();
8
9let area = 0;
10
11function calculateArea(length, width) {
12 // this function calculates the area of a rectangle
13
14 // process
15 const area = length * width
16
17 return area
18}
19
20// input
21const lengthFromUser = parseInt(prompt("Enter the length of a rectangle (cm): "))
22const widthFromUser = parseInt(prompt("Enter the width of a rectangle (cm): "))
23console.log();
24
25// call functions
26area = calculateArea(lengthFromUser, widthFromUser)
27
28// output
29console.log(`The area is ${area} cm²`)
30
31console.log("\nDone.")
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module calculates area of a rectangle
6"""
7
8
9def calculate_area(length: int, width: int) -> int:
10 """The calculate_area() function calculates area of a rectangle, returns int."""
11
12 # process
13 area = length * width
14
15 # output
16 return area
17
18
19def main() -> None:
20 """The main() function just calls other functions, returns None."""
21
22 # input
23 length_from_user = int(input("Enter the length of a rectangle (cm): "))
24 width_from_user = int(input("Enter the width of a rectangle (cm): "))
25 print("")
26
27 # call functions
28 area = calculate_area(width = width_from_user, length = length_from_user)
29
30 # output
31 print(f"The area is {area} cm²")
32
33 print("\nDone.")
34
35
36if __name__ == "__main__":
37 main()
Example Output
