Chapter 4: Mastering Loops
In our previous chapters, we learned how to store information and how to make logical decisions. However, one of the greatest strengths of a computer is its ability to perform the same task thousands—or even millions—of times without getting tired. This capability is known as Looping. In C, loops are fundamental to tasks ranging from processing arrays of data to running game engines.
The Three Pillars of Iteration
C provides three primary types of loops, each designed for a different scenario. Choosing the right one makes your code significantly cleaner and more efficient.
1. The For Loop
The for loop is used when you know in advance how many times you want to execute a block of code. It consists of three parts: initialization, the condition, and the increment/decrement.
for (int i = 0; i < 10; i++) {
printf("Iteration: %d\n", i);
}
Here, i acts as our counter. The loop starts at 0, checks if it is less than 10, executes the print statement, and then adds 1 to i. This cycle continues until the condition becomes false.
2. The While Loop
The while loop is used when the number of iterations is not known beforehand. It simply checks a condition, and as long as that condition remains true, it keeps running. This is perfect for reading user input or waiting for a specific event to occur.
int x = 5;
while (x > 0) {
printf("Countdown: %d\n", x);
x--;
}
3. The Do-While Loop
The do-while loop is a unique variant. Unlike the standard while loop, which checks the condition *before* executing the code, the do-while loop executes the code *first* and then checks the condition. This guarantees that your code runs at least once, regardless of the initial condition.
int x = 0;
do {
printf("This runs at least once!\n");
} while (x > 0);
Control Statements: Break and Continue
Sometimes you need to exit a loop early or skip a specific iteration. The break statement allows you to jump out of a loop entirely. The continue statement skips the remainder of the current loop iteration and jumps directly to the next one.
The Danger of Infinite Loops
A common error is the "Infinite Loop." This occurs when the condition for a while or for loop never becomes false. This forces the program to run forever, consuming CPU resources until the OS kills it. Always verify that your counter or condition will eventually change in a way that terminates the loop.
Common Pitfalls
- Off-By-One Errors: Using
<=instead of<(or vice versa) is a classic mistake. Always trace your loops carefully. - Modifying the Counter Inside: Manually changing your loop counter variable inside the loop body can cause unpredictable behavior.
- Missing Semicolon: Accidentally putting a semicolon after a
fororwhilestatement creates an empty loop body, which often causes logical bugs that are hard to spot.
Try It Yourself
- Write a program that calculates the sum of all numbers from 1 to 100 using a
forloop. - Create a "guessing game" where the computer asks the user to enter a specific number, and the program keeps looping until the user guesses correctly using a
whileloop.
Choosing the Right Loop
C gives you three main loop types. Use a for loop when you know exactly how many times to repeat, a while loop when the number of repetitions depends on a condition, and a do-while loop when the code must run at least once before checking the condition.
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
CodeMaster Academy