Course contentsShow
← C
Lesson 287 of 1,2194. Control FlowFree lesson

Using non-unit increments (e.g., i += 2)

Using non-unit increments (e.g., i += 2)

What you'll learn: How to control the "step size" of your loop to skip numbers or count by specific intervals.

In our previous lessons, we used i++ to move through a loop one step at a time. This is like walking up a staircase and hitting every single step. However, sometimes you want to take the stairs two at a time, or perhaps jump down five steps at once. In C, you aren't restricted to counting by ones; you can change your counter by any amount using the assignment operators you’ve already learned.

Changing the step size

The third part of the for loop declaration is the update expression. While i++ (increment by 1) is the most common choice, you can use any mathematical expression here.

If you want to count only even numbers, you don't need to check every number with an if statement. Instead, you can simply tell the loop to add 2 to the counter every time it finishes a cycle.

#include <stdio.h>

int main() {
    // Printing even numbers from 0 to 10
    // We start at 0, and instead of i++, we use i += 2
    for (int i = 0; i <= 10; i += 2) {
        printf("%d ", i);
    }
    
    // The output will be: 0 2 4 6 8 10
    return 0;
}

Why use non-unit increments?

Think of a non-unit increment as a filter for your loop. If you are writing a program to simulate a clock, you might increment a "seconds" variable by 60 to jump exactly one minute at a time. If you are calculating a discount for every fifth item in a list, you could use i += 5.

This approach is much more efficient than looping through every single number and using "if" logic to see if you should act. By changing the increment, you are telling the computer to skip the unnecessary work entirely.

Going backwards or jumping further

This flexibility applies to all directions. If you want to countdown from 100 to 0 by tens, you would use i -= 10. If you wanted to double a value every time, you could even use i *= 2. The update expression is simply a command that runs at the end of every loop iteration to prepare the counter for the next round.

Key takeaway

By using expressions like i += 2 or i -= 10 in your loop header, you control the "stride" of the loop, allowing you to skip values efficiently.