Resources | Subject Notes | Computer Science
This section focuses on how to write values into and read values from an array using iteration (loops) in a programming context.
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.
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
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
The following Python code demonstrates how to write values into an array and then read and print those values using iteration.
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)
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
for
loops are commonly used for array iteration.