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. It turnes 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. From the previous example of summing up all the values in an array, a For Each loop would look like the following function:

template<size_t N>
int SumOfNumbers(std::array<int, N> listOfNumbers) {
    // this function adds up all the numbers in a list

    int total = 0;

    // add up each element in an array, listOfNumbers
    for (int aSingleElement : listOfNumbers){
        total += aSingleElement;
    }

    return total;
}
// declare an array as a parameter in a function
// declare an array as a parameter in a function
// declare an array as a parameter in a function
def sum_of_numbers(list_of_numbers):
    # this functions uses a for ... in loop

    total = 0

    for a_single_number in list_of_numbers:
        total += a_single_number

    return total
// declare an array as a parameter in a function
// declare an array as a parameter in a function