Imagine you want to print "Hello" 100 times.
Writing printf() 100 times would be a terrible idea!
Instead, we can tell the computer:
"Repeat this task until a certain condition is met."
This is exactly what loops do.
What is a Loop?
A loop is a programming structure that repeatedly executes a block of code as long as a specified condition is satisfied.
For example:
for (int i = 1; i <= 5; i++)
{
printf("Hello\n");
}
Output:
Hello
Hello
Hello
Hello
Hello
Instead of writing the same statement five times, we wrote it once and used a loop.
Types of Loops in C
C provides three main types of loops:
Loop | Best Used When |
|---|---|
| You generally know how many times to repeat |
| Repetition depends mainly on a condition |
| The code must execute at least once |
1. for Loop
The for loop is commonly used when we know the number of repetitions.
Syntax
for (initialization; condition; update)
{
// code
}
Example:
for (int i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
Output:
1
2
3
4
5
Here:
int i = 1→ initializationi <= 5→ conditioni++→ update
2. while Loop
A while loop executes the code as long as its condition is true.
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i++;
}
Output:
1
2
3
4
5
The condition is checked before each iteration.
3. do-while Loop
The do-while loop is slightly different.
It executes the code at least once, because the condition is checked after the code runs.
int i = 1;
do
{
printf("%d\n", i);
i++;
}
while (i <= 5);
Output:
1
2
3
4
5
Even if the condition is initially false, the code inside do executes once.
For example:
int i = 10;
do
{
printf("Hello");
}
while (i < 5);
Hello is still printed once.
for vs while vs do-while
Feature |
|
|
|
|---|---|---|---|
Condition checked | Before iteration | Before iteration | After iteration |
Guaranteed to run once? | No | No | Yes |
Common use | Known repetitions | Condition-based repetition | Must execute once |
Loop Control Statements
C also provides break and continue to control loops.
break
break immediately stops the loop.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
break;
printf("%d\n", i);
}
Output:
1
2
continue
continue skips the current iteration and moves to the next one.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
printf("%d\n", i);
}
Output:
1
2
4
5
In Simple Words
A loop allows us to repeat a block of code without writing the same code again and again.
The three main loops in C are:
for → known number of repetitions
while → condition-based repetition
do-while → executes at least once
Once you understand loops, you'll be able to solve many repetitive programming problems much more efficiently.