Resources | Subject Notes | Computer Science
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.
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.
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.
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
.
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.
Let's look at some practical examples of using loops to process arrays.
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
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
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
Consider exploring more complex array operations, such as: