Array as a Parameter
We know from the previous section that functions are a great way to ensure that your program is modular in its design. Any time a piece of code needs to be repeated more than once or twice, a function might want to be used. When we use functions, we passed variables by value (making a copy) or by reference (passing the pointer); so that the function can do some process on the data. We normally pass variables like integers, strings, and floats but we have seen that you can pass any object, like an image. Since an array is just a variable that happens to hold several values and not just one, it also can be passed to a function, either by value or by reference (depending what the language will allow.).
There is some disagreement in the computer world whether it is wise to pass arrays, especially large ones with many values in them, by value. This is because you are making a complete copy of the array and it could take up a large quantity of memory. Other programmers do not like the idea of passing by reference if you do not want the original array to change, because there is always the risk that you or someone that comes after you, will change the array by accident. They argue that modern computers have so much memory these days (as compared to the “old days”) that the risk of changing the original array is not worth the potential memory usage. We will continue to pass variables into parameters by value, unless there is a really good reason that you want to pass the object in by reference (or i the programming language only lets you pass it in my reference).
To pass an array into a function, you declare the array inside the name of your function, just like you have been doing for regular variable, but you do not place any brackets or a number inside brackets, like when you were declaring your array normally. This is because the function does not know exactly how many elements the array will have. If you had to set it to a fixed amount, your function would not be very flexible. When the array is passed into the function, it will determine how many elements it has and an appropriate array variable with that many elements will be created.
To declare an array as a parameter in a function, it would look like this:
// In C you must pass in the size of the array to a function, first
int sumOfNumbers(int lengthOfArray, int arrayOfNumbers[lengthOfArray]) {
// In C++, an array is passed by reference to a function
// (template is used to find the length of the array)
template<int arraySize>
int sumOfNumbers(int (&arrayOfNumbers)[arraySize]) {
// In C#, an array is passed by reference to a function
static int SumOfNumbers(int[] arrayOfNumbers) {
// In Go, an array is passed by value to a function
func sumOfNumbers(arrayOfNumbers []int) int {
// In Java, an array is passed by value to a function,
// but it's important to note that the value being passed is actually a reference to the array.
// This means that modifications made to the array elements within the function will affect the original array outside the function.
public static int sumOfNumbers(int[] arrayOfNumbers) {
// In JavaScript, an array is passed by value to a function,
// but it's important to note that the value being passed is actually a reference to the array.
// This means that modifications made to the array elements within the function will affect the original array outside the function.
function sumOfNumbers(arrayOfNumbers) {
# in python an array is passed by reference to a function
def sum_of_numbers(array_of_numbers: List[int]) -> int:
To pass an array into this function as a parameter, it would look like this:
int sum = sumOfNumbers(lengthOfArray, numberList);
int sum = sumOfNumbers(numberList);
int sum = SumOfNumbers(numberList);
total := sumOfNumbers(arrayOfNumbers[:])
int total = sumOfNumbers(arrayOfNumbers);
const sum = sumOfNumbers(numberList);
sum = sum_of_numbers(random_numbers)
Here is a complete example of creating an array and passing it as a parameter to a function:
Code for Creating an Array
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 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses an array as a parameter
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// In C you must pass in the size of the array to a function, first
int sumOfNumbers(int lengthOfArray, int arrayOfNumbers[lengthOfArray]) {
// this function adds up all of the numbers in the array
int total = 0;
int counter = 0;
while (counter < lengthOfArray) {
total += arrayOfNumbers[counter];
counter++;
}
return total;
}
int main() {
// this function uses an array
// remember in C you must know the array size at compile time
int arraySize = 10;
int numberList[arraySize];
int seed = time(NULL);
// input
srand(seed);
for (int counter = 0; counter < arraySize; counter++) {
int aSingleRandomNumber = rand_r(&seed) % 100;
numberList[counter] = aSingleRandomNumber;
printf("The random number is: %d\n", aSingleRandomNumber);
}
printf("\n");
// call function
int lengthOfArray = sizeof(numberList) / sizeof(numberList[0]);
int sum = sumOfNumbers(lengthOfArray, numberList);
// output
printf("The sum of all the numbers is: %d\n", sum);
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
42
43
44
45
46
47
48
49
50
51 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses an array as a parameter
#include <iostream>
#include <cstdlib>
#include <ctime>
// In C++, an array is passed by reference to a function
// (template is used to find the length of the array)
template<int arraySize>
int sumOfNumbers(int (&arrayOfNumbers)[arraySize]) {
// this function adds up all of the numbers in the array
int total = 0;
int counter = 0;
while (counter < arraySize) {
total += arrayOfNumbers[counter];
counter++;
}
return total;
}
int main() {
// this function uses an array
int numberList[10];
unsigned int seed = time(NULL);
srand(seed);
// input
for (int counter = 0; counter < 10; counter++) {
numberList[counter] = rand_r(&seed) % 100;
std::cout << "The random number is: " << numberList[counter]
<< std::endl;
}
std::cout << "" << std::endl;
// call functions
int sum = sumOfNumbers(numberList);
// output
std::cout << "The sum of all the numbers is: " << sum << std::endl;
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
42
43
44
45
46
47 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses an array as a parameter
*/
using System;
/*
* The Program class
* Contains all methods for performing basic variable usage
*/
class Program {
// In C#, an array is passed by reference to a function
static int SumOfNumbers(int[] arrayOfNumbers) {
// this function adds up all of the numbers in the array
int total = 0;
int counter = 0;
int lengthOfArray = arrayOfNumbers.Length;
while (counter < lengthOfArray) {
total += arrayOfNumbers[counter];
counter++;
}
return total;
}
public static void Main (string[] args) {
int[] numberList = new int[10];
Random rand = new Random();
// input
for (int counter = 0; counter < 10; counter++) {
numberList[counter] = rand.Next(1, 100);
Console.WriteLine("The random number is: {0}", numberList[counter]);
}
Console.WriteLine();
// call function
int sum = SumOfNumbers(numberList);
// output
Console.WriteLine("The sum of all the numbers is: {0}", sum);
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
43
44
45
46
47
48 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses an array as a parameter
*/
package main
import (
"fmt"
"math/rand"
"time"
)
// In Go, an array is passed by value to a function
func sumOfNumbers(arrayOfNumbers []int) int {
// this function adds up all of the numbers in the array
total := 0
counter := 0
while counter < len(arrayOfNumbers) {
total += arrayOfNumbers[counter]
counter++
}
return total
}
func main() {
// this function uses an array as a parameter
rand.Seed(time.Now().UnixNano())
var arrayOfNumbers [10]int
// input
for counter := 0; counter < len(arrayOfNumbers); counter++ {
arrayOfNumbers[counter] = rand.Intn(100) + 1
fmt.Println("The number is:", arrayOfNumbers[counter])
}
fmt.Println("")
// call function
total := sumOfNumbers(arrayOfNumbers[:])
// output
fmt.Println("The sum of all the numbers is:", total)
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
57
58
59
60
61
62
63
64
65
66 | /*
* This program uses an array as a parameter
*
* @author Mr Coxall
* @version 1.0
* @since 2020-09-01
*/
import java.util.Arrays;
import java.util.Random;
final class Main {
/**
* This function calculates the sum of an array.
*
* @param args array of integers
*/
// In Java, an array is passed by value to a function,
// but it's important to note that the value being passed is actually a reference to the array.
// This means that modifications made to the array elements within the function will affect the original array outside the function.
public static int sumOfNumbers(int[] arrayOfNumbers) {
// this function adds up all of the numbers in the array
int total = 0;
int counter = 0;
while (counter < arrayOfNumbers.length) {
total += arrayOfNumbers[counter];
counter++;
}
return total;
}
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) {
int[] arrayOfNumbers = new int[10];
long seed = System.currentTimeMillis();
Random rand = new Random(seed);
// input
for (int counter = 0; counter < arrayOfNumbers.length; counter++) {
arrayOfNumbers[counter] = rand.nextInt(100) + 1;
System.out.println("The random number is: " + arrayOfNumbers[counter]);
}
System.out.println();
// Call function
int total = sumOfNumbers(arrayOfNumbers);
// output
System.out.println("\nThe sum of the numbers is: " + total);
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
32
33
34
35
36
37
38
39
40
41
42
43 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses an array as a parameter
*/
// In JavaScript, an array is passed by value to a function,
// but it's important to note that the value being passed is actually a reference to the array.
// This means that modifications made to the array elements within the function will affect the original array outside the function.
function sumOfNumbers(arrayOfNumbers) {
// this function adds up all of the numbers in the array
let total = 0;
let counter = 0;
while (counter < arrayOfNumbers.length) {
total += arrayOfNumbers[counter];
counter++;
}
return total;
}
// input
const numberList = [];
const seed = new Date().getTime();
const rand = require('random-seed').create(seed);
// input
for (let counter = 0; counter < 10; counter++) {
const randomNumber = rand.intBetween(1, 100);
numberList.push(randomNumber);
console.log("The random number is: " + randomNumber);
}
console.log("\n");
// call the function
const sum = sumOfNumbers(numberList);
// output
console.log("The sum of all the numbers is: " + sum);
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
38
39
40
41
42
43
44
45
46
47
48 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses an array as a parameter
"""
import random
from typing import List
# in python an array is passed by reference to a function
def sum_of_numbers(array_of_numbers: List[int]) -> int:
"""The sum_of_numbers() function calculates the sum of numbers in a list, returns the sum as int."""
total = 0
for counter in range(0, len(array_of_numbers)):
total += array_of_numbers[counter]
return total
def main() -> None:
"""The main() function just calls other functions, returns None."""
random_numbers = []
sum = 0
# input
for loop_counter in range(0, 10):
a_single_number = random.randint(1, 100)
random_numbers.append(a_single_number)
print(f"The random number is: {a_single_number}")
print("")
# process
sum = sum_of_numbers(random_numbers)
# output
print(f"The sum of all the numbers is: {sum}")
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output