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}

Example Output

Code example output