Imagine having to print the numbers from 1 to 100 using nothing but individual printf statements. Not only would this involve writing a hundred nearly identical lines of code, but changing the range later would mean manually editing every single one of them. Loops exist precisely to eliminate this kind of repetitive, error-prone work by allowing a block of code to run multiple times automatically, based on a condition you define.
Loops are one of the concepts that make programming genuinely powerful, since they let a small amount of code accomplish tasks that would otherwise require enormous amounts of repeated instructions. Once you understand how loops work, you will find yourself using them constantly, whether you are processing arrays, validating user input, or performing repeated calculations.
In this tutorial, you will learn how the for loop, while loop, and do-while loop each work, how they differ from one another, how to use break and continue to control loop execution more precisely, how nested loops function, and how to recognize and avoid accidentally writing an infinite loop.
Loops solve the problem of repeating a block of code without duplicating that code physically within the program. Instead of writing the same instruction over and over, a loop describes the instruction once, along with a condition that determines how many times it should run.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("CS Engineering Gyan Tutorial %d\n", i);
}
return 0;
}
CS Engineering Gyan Tutorial 1 CS Engineering Gyan Tutorial 2 CS Engineering Gyan Tutorial 3 CS Engineering Gyan Tutorial 4 CS Engineering Gyan Tutorial 5
This single loop replaces what would otherwise require five separate printf statements, and the behavior can be easily adjusted by simply changing the loop's condition.
The for loop is typically the first loop beginners learn, largely because it combines initialization, condition checking, and updating into a single, compact line, making it especially useful when the number of repetitions is known in advance.
for (initialization; condition; update) {
// code to repeat
}
#include <stdio.h>
int main() {
int totalViews = 0;
int day;
for (day = 1; day <= 7; day++) {
totalViews += 500;
}
printf("Total views after one week: %d", totalViews);
return 0;
}
Total views after one week: 3500
The three parts of the for loop are evaluated in a specific order: the initialization runs once at the very beginning, the condition is checked before every repetition, and the update runs after each repetition completes, right before the condition is checked again.
The while loop is useful in situations where the number of repetitions is not known ahead of time, and instead depends entirely on a condition that may be influenced by user input or other changing data during execution.
while (condition) {
// code to repeat
}
#include <stdio.h>
int main() {
int subscribers = 8000;
while (subscribers < 10000) {
subscribers += 500;
printf("Subscribers: %d\n", subscribers);
}
return 0;
}
Subscribers: 8500 Subscribers: 9000 Subscribers: 9500 Subscribers: 10000
Here, the loop keeps running for as long as the subscriber count remains below the target, and it naturally stops the moment the condition becomes false, without needing to know in advance exactly how many repetitions will be required.
The do-while loop behaves almost identically to the while loop, with one important difference: the condition is checked after the loop body runs, rather than before. This guarantees that the loop body executes at least once, even if the condition turns out to be false immediately.
do {
// code to repeat
} while (condition);
#include <stdio.h>
int main() {
int attempt = 1;
do {
printf("Upload attempt %d\n", attempt);
attempt++;
} while (attempt <= 3);
return 0;
}
Upload attempt 1 Upload attempt 2 Upload attempt 3
This guaranteed first execution makes do-while particularly useful for situations like menu-driven programs, where an option needs to be displayed to the user at least once before checking whether they want to continue.
| Loop Type | Condition Checked | Best Suited For |
|---|---|---|
| for | Before each repetition, combined with initialization and update. | Situations where the number of repetitions is known in advance. |
| while | Before each repetition. | Situations where repetition depends on a condition that may change unpredictably. |
| do-while | After each repetition. | Situations where the loop body must run at least once regardless of the condition. |
The break statement immediately stops a loop from continuing, regardless of what the loop's condition would otherwise evaluate to. It is commonly used when a specific situation is detected that makes further repetition unnecessary or undesirable.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
printf("Processing item %d\n", i);
}
return 0;
}
Processing item 1 Processing item 2 Processing item 3 Processing item 4 Processing item 5
Even though the loop was set up to run all the way to 10, the break statement forces it to exit early once the value of i reaches 6, skipping the remaining iterations entirely.
Unlike break, which exits the loop entirely, continue skips only the remainder of the current iteration and moves directly to the next one, without terminating the loop as a whole.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("Value: %d\n", i);
}
return 0;
}
Value: 1 Value: 2 Value: 4 Value: 5
When i reaches 3, the continue statement skips the printf call for that particular iteration, but the loop still continues running normally for the remaining values.
A nested loop is a loop placed inside another loop, allowing a program to handle repeated patterns that involve two or more dimensions, such as printing a grid or comparing every pair of elements within a dataset.
#include <stdio.h>
int main() {
int row, col;
for (row = 1; row <= 3; row++) {
for (col = 1; col <= 3; col++) {
printf("(%d,%d) ", row, col);
}
printf("\n");
}
return 0;
}
(1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
For every single repetition of the outer loop, the entire inner loop runs completely from start to finish, which is why nested loops are frequently used for tasks involving grids, tables, or comparisons between multiple sets of values.
An infinite loop occurs when a loop's condition never becomes false, causing it to run indefinitely unless deliberately interrupted using a break statement or by terminating the program manually. While infinite loops are sometimes created intentionally, they are far more often the result of a mistake.
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
// count is never updated here, creating an infinite loop
}
return 0;
}
In this example, since the variable count is never increased inside the loop, the condition remains true forever, causing the program to print the same value endlessly until it is manually stopped. This highlights why it is essential to ensure that a loop's condition can eventually become false.
| Mistake | Correct Practice |
|---|---|
| Forgetting to update the loop control variable, resulting in an infinite loop. | Always ensure the variable used in the condition is updated somewhere within the loop body. |
| Placing a semicolon immediately after the for loop's parentheses by mistake. | Avoid adding a semicolon right after the loop declaration, since it creates an empty loop body that runs with no effect. |
| Confusing the behavior of break and continue. | Remember that break exits the loop entirely, while continue only skips the current iteration. |
| Using do-while when a while loop would be more appropriate. | Reserve do-while specifically for cases where the loop body must execute at least once regardless of the condition. |
Loops transform repetitive, error-prone code into concise, flexible logic that can adapt to different amounts of repetition without requiring any structural changes. The for loop excels when the number of repetitions is known ahead of time, the while loop handles situations driven by changing conditions, and the do-while loop guarantees at least one execution regardless of the condition.
In this tutorial, you learned how each of these loop types works, how break and continue provide finer control over loop execution, how nested loops handle multi-dimensional repetition, and how to recognize and avoid accidentally creating an infinite loop. With loops now part of your toolkit, you are ready to explore arrays, which work especially well alongside loops when processing collections of related data.