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
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 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program calculates the area of a rectangle
#include <stdio.h>
int calculateArea(int length, int width) {
// this function calculates the area of a rectangle
// process
int area = length * width;
return area;
}
int main() {
// this function does the input and output
int area = 0;
// input
printf("Enter the length of a rectangle (cm): ");
int lengthFromUser;
scanf("%d", &lengthFromUser);
printf("Enter the width of a rectangle (cm): ");
int widthFromUser;
scanf("%d", &widthFromUser);
printf("\n");
// call functions
area = calculateArea(lengthFromUser, widthFromUser);
// output
printf("The area is %d 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
38
39
40
41 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program calculates the area of a rectangle
#include <iostream>
int calculateArea(int length, int width) {
// this function calculates the area of a rectangle
// process
int area = length * width;
return area;
}
int main() {
// this function does the input and output
int area = 0;
int perimeter = 0;
// input
std::cout << "Enter the length of a rectangle (cm): ";
int lengthFromUser;
std::cin >> lengthFromUser;
std::cout << "Enter the width of a rectangle (cm): ";
int widthFromUser;
std::cin >> widthFromUser;
std::cout << std::endl;
// call functions
area = calculateArea(lengthFromUser, widthFromUser);
// 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
40
41 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program calculates the area of a rectangle
*/
using System;
/*
* The Program class
* Contains all methods for performing basic variable usage
*/
class Program {
static int calculateArea(int length, int width) {
// this function calculates the area of a rectangle
// process
int area = length * width;
return area;
}
public static void Main (string[] args) {
// this function does the input and output
int area = 0;
// input
Console.Write("Enter the length of a rectangle (cm): ");
int lengthFromUser = int.Parse(Console.ReadLine());
Console.Write("Enter the width of a rectangle (cm): ");
int widthFromUser = int.Parse(Console.ReadLine());
Console.WriteLine("");
// call functions
area = calculateArea(width: widthFromUser, length: lengthFromUser);
// 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
41
42 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses user defined functions
*/
package main
import (
"fmt"
)
func calculateArea(length int, width int) {
// this function calculates the area of a rectangle
// process
area := length * width
return area
}
func main() {
// this function does the input and output
var area = 0
// input
var length_from_user, width_from_user int
fmt.Print("Enter the length of a rectangle (cm): ")
fmt.Scanln(&length_from_user)
fmt.Print("Enter the width of a rectangle (cm): ")
fmt.Scanln(&width_from_user)
fmt.Println()
// call functions
area = calculateArea(length_from_user, width_from_user)
// 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
55
56 | /*
* This program calculates area of rectangle
*
* @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 int calculateArea(int length, int width) {
// process
int area = length * width;
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 void main(final String[] args) {
// this function does the input and output
int area = 0;
// input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of a rectangle (cm): ");
int lengthFromUser = scanner.nextInt();
System.out.print("Enter the width of a rectangle (cm): ");
int widthFromUser = scanner.nextInt();
System.out.println();
// call functions
area = calculateArea(lengthFromUser, widthFromUser);
// 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
29
30
31 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program calculates the area of a rectangle
*/
const prompt = require('prompt-sync')();
let area = 0;
function calculateArea(length, width) {
// this function calculates the area of a rectangle
// process
const area = length * width
return area
}
// input
const lengthFromUser = parseInt(prompt("Enter the length of a rectangle (cm): "))
const widthFromUser = parseInt(prompt("Enter the width of a rectangle (cm): "))
console.log();
// call functions
area = calculateArea(lengthFromUser, widthFromUser)
// 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 area of a rectangle
"""
def calculate_area(length: int, width: int) -> int:
"""The calculate_area() function calculates area of a rectangle, returns int."""
# process
area = length * width
# output
return area
def main() -> None:
"""The main() function just calls other functions, returns None."""
# input
length_from_user = int(input("Enter the length of a rectangle (cm): "))
width_from_user = int(input("Enter the width of a rectangle (cm): "))
print("")
# call functions
area = calculate_area(width = width_from_user, length = length_from_user)
# output
print(f"The area is {area} cm²")
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output