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

Programming: Working with Arrays

Writing Values into an Array Using Iteration

Imagine an array as a row of lockers 🗂️. Each locker has a unique number (the index) and can hold a single item. Writing values into the array is like putting a note in each locker. We use a loop to go through each locker one by one and place the note inside.

  1. Decide how many lockers you need – that’s the array’s size.
  2. Use a for loop to iterate over each index from 0 to size-1.
  3. Inside the loop, assign a value to the array at the current index:
    for (let i = 0; i < size; i++) {
        array[i] = i * 2; // example: store double the index
    }
        
  4. After the loop finishes, every locker holds a value.

In LaTeX notation, the array after filling looks like: $$\mathbf{A} = [a_0, a_1, \dots, a_{n-1}]$$ where each \(a_i\) is the value stored at index \(i\).

Reading Values from an Array Using Iteration

Now that our lockers are filled, we can read the notes one by one. This is useful when we want to display all values, find a specific value, or perform calculations on each element.

  1. Use a for loop to iterate over each index again.
  2. Inside the loop, retrieve the value at the current index and do something with it (e.g., print, sum, or check a condition).
    for (let i = 0; i < array.length; i++) {
        console.log(`Index ${i} contains ${array[i]}`);
    }
        
  3. When the loop ends, you have processed every element.

Below is a visual representation of an array after writing and reading operations. The table shows each index and its stored value.

Index Value
0 0
1 2
2 4
3 6

Key Takeaways:

  • Arrays store values at specific indices.
  • Iteration (loops) lets you write to or read from each array element efficiently.
  • Use clear variable names and comments to keep your code understandable.

Happy coding! 🚀

Revision

Log in to practice.

1 views 0 suggestions