Counting backwards with decrement operators
What you'll learn: How to use the decrement operator within a for loop to make your program count down instead of up.
The Countdown Logic
In previous lessons, we used i++ to add one to our counter during each loop cycle. But what if you are building a rocket launch sequencer or a timer that needs to hit zero? To do this, we flip the script on the three parts of the for loop.
Think of it like walking down a flight of stairs. You start at the top (initialization), check to see if you’ve reached the ground floor yet (condition), and take one step down at a time (decrement).
Flipping the Loop
To count backwards, we make three specific changes to the standard loop structure:
- Start High: Set your variable to the starting maximum value (e.g.,
int i = 10). - Check the Floor: Use the "greater than" (
>) or "greater than or equal to" (>=) operator. The loop keeps running as long asiis still above your target. - Step Down: Use the decrement operator (
i--) to subtract one from the variable every time the code block finishes.
Here is how a 5-second countdown looks in C code:
#include <stdio.h>
int main() {
// Start at 5, keep going while i is at least 1, subtract 1 each time
for (int i = 5; i >= 1; i--) {
printf("%d...\n", i);
}
printf("Blast off!\n");
return 0;
}
Why the Condition Matters
When counting up, we usually use i < 10. If you accidentally use that while counting down from 5, the loop will never start because 5 is not less than 10. Conversely, if you set a condition that is always true (like i > 0 while adding to i), your loop will run forever. Always ensure your condition points toward your destination.
Key takeaway
To count backwards, initialize your variable to a high number, use a "greater than" comparison, and apply the -- operator.