Write values into, and read values from, an array using iteration

Resources | Subject Notes | Computer Science

Arrays and Iteration - IGCSE Computer Science

Arrays and Iteration

Objective

This section focuses on how to write values into and read values from an array using iteration (loops) in a programming context.

What is an Array?

An array is a data structure that stores a collection of items of the same data type. Each item in the array is referred to as an element and is accessed using an index (position) within the array. Array indices typically start from 0.

Writing Values into an Array

To write values into an array, we use a loop (like a for loop) to iterate through the array indices and assign values to the corresponding elements.

Example (pseudocode):

        FOR i = 0 TO array_length - 1
            array[i] = new_value
        ENDFOR
    

Reading Values from an Array

To read values from an array, we also use a loop to iterate through the array indices and access the element at each index.

Example (pseudocode):

        FOR i = 0 TO array_length - 1
            current_value = array[i]
            // Process current_value
        ENDFOR
    

Example Program (Python)

The following Python code demonstrates how to write values into an array and then read and print those values using iteration.

Suggested diagram: An array with elements labeled with their indices.
Iteration Index Value to Write Array Element After Write
Initial State - - -
Iteration 1 0 10 10
Iteration 2 1 20 10, 20
Iteration 3 2 30 10, 20, 30

Python Code:

def write_and_read_array(array_length):
    my_array = [0] * array_length  # Initialize an array of the specified length with zeros
    for i in range(array_length):
        my_array[i] = i * 10  # Write values (10, 20, 30) into the array

    print("Array elements after writing:")
    for i in range(array_length):
        print(f"Element at index {i}: {my_array[i]}")

write_and_read_array(3)
    

Example Output

The output of the Python code above will be:

Array elements after writing:
Element at index 0: 0
Element at index 1: 10
Element at index 2: 20
    

Key Concepts

  • Iteration: Repeating a block of code for a specific number of times.
  • Looping Structures: for loops are commonly used for array iteration.
  • Array Indexing: Accessing elements in an array using their index (position).