Use loops to process arrays

Resources | Subject Notes | Computer Science

Arrays and Loops

This section explores how to effectively use loops to process elements within arrays in computer science. Arrays are fundamental data structures used to store collections of items of the same data type. Understanding how to iterate through and manipulate array elements is crucial for many programming tasks.

What is an Array?

An array is a contiguous block of memory locations used to store a sequence of elements. Each element in an array is accessed using an index, starting from 0.

For example, an array of integers might be represented as:

[10, 20, 30, 40, 50]

Here, the index 0 refers to 10, index 1 refers to 20, and so on.

Iterating Through Arrays with Loops

Loops are essential for processing each element of an array. The most common loop types used for this purpose are for loops and while loops.

For Loops

A for loop is ideal when you know the number of iterations required (i.e., the size of the array). It provides a concise way to access each element using its index.

Example (Python):

for i in range(len(my_array)):
    print(my_array[i])

In this example, len(my_array) gives the number of elements in the array. The range() function generates a sequence of numbers from 0 up to (but not including) the length of the array. The loop variable i takes on each value in that sequence, and we use it to access the element at index i.

While Loops

A while loop is useful when the number of iterations depends on a condition, rather than a fixed number of elements. This can be helpful if you need to process the array until a certain condition is met.

Example (Python):

i = 0
while i < len(my_array):
    print(my_array[i])
    i += 1

Here, the loop continues as long as i is less than the length of the array. Inside the loop, we access the element at index i and then increment i to move to the next element.

Array Processing Examples

Let's look at some practical examples of using loops to process arrays.

Example 1: Summing the Elements of an Array

Calculate the sum of all the numbers in an array.

Array Sum
[1, 2, 3, 4, 5] 15
[10, 20, 30] 60

Example (Python):

def sum_array(arr):
    total = 0
    for num in arr:
        total += num
    return total

Example 2: Finding the Largest Element in an Array

Find the largest number in an array.

Array Largest Element
[5, 2, 8, 1, 9] 9
[10, 5, 20, 15] 20

Example (Python):

def find_largest(arr):
    largest = arr[0]
    for num in arr:
        if num > largest:
            largest = num
    return largest

Example 3: Multiplying each element by a scalar

Multiply each element of an array by a given scalar value.

Array Scalar Modified Array
[1, 2, 3] 2 [2, 4, 6]
[4, 5, 6] -1 [-4, -5, -6]

Example (Python):

def multiply_array(arr, scalar):
    for i in range(len(arr)):
        arr[i] *= scalar
    return arr

Important Considerations

  • Array Indexing: Remember that array indices start from 0. Accessing an element with an invalid index will result in an error.
  • Array Size: Be mindful of the array's size when using loops. Avoid going beyond the bounds of the array.
  • Data Types: Ensure that the data type of the loop variable is compatible with the data type of the array elements.
Suggested diagram: Illustrates a simple array with elements and their corresponding indices.

Further Exploration

Consider exploring more complex array operations, such as:

  • Searching for a specific element in an array.
  • Sorting an array.
  • Reversing an array.