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// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program uses an array as a parameter
6
7#include <iostream>
8#include <cstdlib>
9#include <ctime>
10
11
12// In C++, an array is passed by reference to a function
13// (template is used to find the length of the array)
14template<size_t arraySize>
15int sumOfNumbers(int (&arrayOfNumbers)[arraySize]) {
16 // this function adds up all of the numbers in the array, using a For Each loop
17
18 int total = 0;
19 int counter;
20
21 for (int aSingleNumber : arrayOfNumbers) {
22 total += aSingleNumber;
23 }
24
25 return total;
26}
27
28int main() {
29 // this function uses an array
30 int numberList[10];
31 unsigned int seed = time(NULL);
32
33 srand(seed);
34 // input
35 for (int counter = 0; counter < 10; counter++) {
36 numberList[counter] = rand_r(&seed) % 100;
37 std::cout << "The random number is: " << numberList[counter]
38 << std::endl;
39 }
40 std::cout << "" << std::endl;
41
42 // call functions
43 int sum = sumOfNumbers(numberList);
44
45 // output
46 std::cout << "The sum of all the numbers is: " << sum << std::endl;
47
48 std::cout << "\nDone." << std::endl;
49 return 0;
50}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program uses an array as a parameter
4*/
5
6using System;
7
8/*
9 * The Program class
10 * Contains all methods for performing basic variable usage
11*/
12class Program {
13 // In C#, an array is passed by reference to a function
14 static int SumOfNumbers(int[] arrayOfNumbers) {
15 // this function adds up all of the numbers in the array, using a For Each loop
16 int total = 0;
17 int lengthOfArray = arrayOfNumbers.Length;
18
19 foreach (int aSingleNumber in arrayOfNumbers) {
20 total += aSingleNumber;
21 }
22
23 return total;
24 }
25
26 public static void Main (string[] args) {
27 int[] numberList = new int[10];
28 Random rand = new Random();
29
30 // input
31 for (int counter = 0; counter < 10; counter++) {
32 numberList[counter] = rand.Next(1, 100);
33 Console.WriteLine("The random number is: {0}", numberList[counter]);
34 }
35 Console.WriteLine();
36
37 // call function
38 int sum = SumOfNumbers(numberList);
39
40 // output
41 Console.WriteLine("The sum of all the numbers is: {0}", sum);
42
43 Console.WriteLine("\nDone.");
44 }
45}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program uses an array as a parameter
5 */
6
7package main
8
9import (
10 "fmt"
11 "math/rand"
12 "time"
13)
14
15// In Go, an array is passed by value to a function
16func sumOfNumbers(arrayOfNumbers []int) int {
17 // this function adds up all of the numbers in the array, using a For Each loop
18 total := 0
19
20 for _, aSingleNumber := range arrayOfNumbers {
21 total += aSingleNumber
22 }
23
24 return total
25}
26
27func main() {
28 // this function uses an array as a parameter
29 rand.Seed(time.Now().UnixNano())
30 var arrayOfNumbers [10]int
31
32 // input
33 for counter := 0; counter < len(arrayOfNumbers); counter++ {
34 arrayOfNumbers[counter] = rand.Intn(100) + 1
35 fmt.Println("The number is:", arrayOfNumbers[counter])
36 }
37 fmt.Println("")
38
39 // call function
40 total := sumOfNumbers(arrayOfNumbers[:])
41
42 // output
43 fmt.Println("The sum of all the numbers is:", total)
44
45 fmt.Println("\nDone.")
46}
1/*
2 * This program uses an array as a parameter
3 *
4 * @author Mr Coxall
5 * @version 1.0
6 * @since 2020-09-01
7 */
8
9import java.util.Arrays;
10import java.util.Random;
11
12final class Main {
13 /**
14 * This function calculates the sum of an array.
15 *
16 * @param args array of integers
17 */
18 // In Java, an array is passed by value to a function,
19 // but it's important to note that the value being passed is actually a reference to the array.
20 // This means that modifications made to the array elements within the function will affect the original array outside the function.
21 public static int sumOfNumbers(int[] arrayOfNumbers) {
22 // this function adds up all of the numbers in the array, using a For Each loop
23 int total = 0;
24
25 for (int aSingleNumber : arrayOfNumbers) {
26 total += aSingleNumber;
27 }
28
29 return total;
30 }
31
32 private Main() {
33 // Prevent instantiation
34 // Optional: throw an exception e.g. AssertionError
35 // if this ever *is* called
36 throw new IllegalStateException("Cannot be instantiated");
37 }
38
39 /**
40 * Main entry point into program.
41 *
42 * @param args nothing passed in
43 */
44 public static void main(final String[] args) {
45 int[] arrayOfNumbers = new int[10];
46 long seed = System.currentTimeMillis();
47 Random rand = new Random(seed);
48
49 // input
50 for (int counter = 0; counter < arrayOfNumbers.length; counter++) {
51 arrayOfNumbers[counter] = rand.nextInt(100) + 1;
52 System.out.println("The random number is: " + arrayOfNumbers[counter]);
53 }
54 System.out.println();
55
56 // Call function
57 int total = sumOfNumbers(arrayOfNumbers);
58
59 // output
60 System.out.println("\nThe sum of the numbers is: " + total);
61
62 System.out.println("\nDone.");
63 }
64}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program uses an array as a parameter
5 */
6
7
8// In JavaScript, an array is passed by value to a function,
9// but it's important to note that the value being passed is actually a reference to the array.
10// This means that modifications made to the array elements within the function will affect the original array outside the function.
11function sumOfNumbers(arrayOfNumbers) {
12 // this function adds up all of the numbers in the array, using a For Each loop
13 let total = 0;
14
15 for (let aSingleNumber of arrayOfNumbers) {
16 total += aSingleNumber;
17 }
18
19 return total;
20}
21
22// input
23const numberList = [];
24const seed = new Date().getTime();
25const rand = require('random-seed').create(seed);
26
27// input
28for (let counter = 0; counter < 10; counter++) {
29 const randomNumber = rand.intBetween(1, 100);
30 numberList.push(randomNumber);
31 console.log("The random number is: " + randomNumber);
32}
33console.log("\n");
34
35// call the function
36const sum = sumOfNumbers(numberList);
37
38// output
39console.log("The sum of all the numbers is: " + sum);
40
41console.log("\nDone.");
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module uses an array as a parameter
6"""
7
8
9import random
10from typing import List
11
12
13# in python an array is passed by reference to a function
14def sum_of_numbers(array_of_numbers: List[int]) -> int:
15 """The sum_of_numbers() function calculates the sum of numbers in a list, returns the sum as int."""
16
17 total = 0
18
19 for a_single_number in array_of_numbers:
20 total += a_single_number
21
22 return total
23
24
25def main() -> None:
26 """The main() function just calls other functions, returns None."""
27
28 random_numbers = []
29 sum = 0
30
31 # input
32 for loop_counter in range(0, 10):
33 a_single_number = random.randint(1, 100)
34 random_numbers.append(a_single_number)
35 print(f"The random number is: {a_single_number}")
36 print("")
37
38 # process
39 sum = sum_of_numbers(random_numbers)
40
41 # output
42 print(f"The sum of all the numbers is: {sum}")
43
44 print("\nDone.")
45
46
47if __name__ == "__main__":
48 main()
Example Output
