Arrays and For … Each Loops

If you think way back to when we did different types of looping structures, one of the methods to loop was using the For loop. The purpose of the for each loop was that the loop would manage counting for us. It turns out that since an array is a collection of variables held in a common structure, you can use a for loop with it. This type of loop, usually called a For … Each loop, is used when you have a collection of things and you wanted to iterate through each one of them, one at a time. Since an array is a collection of variables, the For … Each loop takes one element out of the array at a time and lets you do something with it. The loop will continue until it has gone through all the elements in the array. The For … Each loop does not need an iterator variable, since the loop manages that counting for you.

From the previous example of summing up all the values in an array, a For Each loop would look like the following:

Code for Using a For … Each loop with an Array

// No For ... Each loop in C
 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
// 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<size_t arraySize>
int sumOfNumbers(int (&arrayOfNumbers)[arraySize]) {
    // this function adds up all of the numbers in the array, using a For Each loop

    int total = 0;
    int counter;

    for (int aSingleNumber : arrayOfNumbers) {
        total += aSingleNumber;
    }

    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
/* 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, using a For Each loop
        int total = 0;
        int lengthOfArray = arrayOfNumbers.Length;

        foreach (int aSingleNumber in arrayOfNumbers) {
            total += aSingleNumber;
        }

        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
/**
 * 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, using a For Each loop
	total := 0

	for _, aSingleNumber := range arrayOfNumbers {
		total += aSingleNumber
	}

	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
/*
 * 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, using a For Each loop
    int total = 0;

    for (int aSingleNumber : arrayOfNumbers) {
      total += aSingleNumber;
    }

    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
/**
 * 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, using a For Each loop
  let total = 0;

  for (let aSingleNumber of arrayOfNumbers) {
      total += aSingleNumber;
  }

  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 a_single_number in array_of_numbers:
        total += a_single_number

    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

Code example output