Course contentsShow
← C
Lesson 406 of 1,2196. Arrays and StringsFree lesson

Modifying all elements in a single pass

Modifying all elements in a single pass

What you'll learn: How to use a for loop to efficiently update every item in an array using its index.

The Assembly Line Analogy

Imagine you are a supervisor at a factory that produces plain white t-shirts. You have a row of ten shirts sitting on a conveyor belt. Your boss tells you that these shirts now need to be dyed blue.

Instead of picking up each shirt randomly, you start at the first position (index 0), dip it in blue dye, put it back, and move to the next position. You repeat this identical action for every spot on the belt until you reach the end. In C, iterating through an array to modify its contents works exactly like this assembly line.

Using the Loop to Update

To modify every element, we use a for loop where the counter variable acts as the "address" or index of the current element. Inside the loop, we access the element using the square bracket [] syntax and assign it a new value.

Because the loop counter (usually i) increments by one each time, we can visit every memory slot in the array in a single, organized pass.

#include <stdio.h>

int main() {
    // A list of item prices that need a $5 discount applied
    float prices[5] = {10.50, 20.00, 15.75, 50.00, 12.25};

    // We use a loop to visit every index from 0 to 4
    for (int i = 0; i < 5; i++) {
        // We take the current value, subtract 5, and save it back
        prices[i] = prices[i] - 5.00;
    }

    // The array now contains: {5.50, 15.00, 10.75, 45.00, 7.25}
    return 0;
}

Why this is powerful

This pattern is the foundation of data processing. Whether you are brightening the pixels in an image, normalizing a set of test scores, or converting a list of temperatures from Celsius to Fahrenheit, the logic remains the same. You don't need to write five or five hundred separate lines of code; you simply write one formula inside a loop, and C applies it to every "container" in your array systematically.

Key takeaway

To modify an entire array, use a for loop where the index variable targets each element for an update in a single pass.