Sometimes a program needs to execute the same block of code multiple times. Writing the same statements repeatedly is highly inefficient and difficult to manage. In C, loops are used to repeat a block of code until a condition becomes false.
C provides three main types of loops: the for loop, the while loop, and the do-while loop.
1. for Loop
The for loop is commonly used when the exact number of iterations is known in advance.
Syntax
for(initialization; condition; update)
{
// code to repeat
}
How It Works
First, the initialization statement executes exactly once. Next, the condition is evaluated. If true, the loop body executes. After the body runs, the update statement executes, and the condition is checked again. The loop stops immediately when the condition becomes false.
Example Program
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
return 0;
}
Console Output
1
2
3
4
5
Execution Flowchart
2. while Loop
The while loop is used when the number of iterations is not fixed beforehand but depends on a dynamically changing condition.
Syntax
while(condition)
{
// code executes as long as condition is true
}
How It Works
The condition is checked before each iteration. As long as it remains true, the loop body executes. If the condition is false initially, the loop body will not execute even once.
Example Program
#include <stdio.h>
int main()
{
int count = 1;
while(count <= 3)
{
printf("Running\n");
count++;
}
return 0;
}
Console Output
Running
Running
Running
Execution Flowchart
3. do-while Loop
The do-while loop is a post-test loop that executes the loop body first and checks the condition afterward.
Syntax
do
{
// code to execute
}
while(condition);
How It Works
Unlike for and while, the do-while loop always executes at least once because the condition is evaluated after the loop body completes.
Example Program
#include <stdio.h>
int main()
{
int value = 1;
do
{
printf("%d\n", value);
value++;
}
while(value <= 3);
return 0;
}
Console Output
1
2
3
Execution Flowchart
Key Differences
Understanding when to use each loop is essential for writing clean, optimized C code:
| Loop Type | Condition Check | Best Used For |
|---|---|---|
| for loop | Before execution (Pre-test) | When the exact number of iterations is known beforehand. |
| while loop | Before execution (Pre-test) | When looping until a specific event or variable change occurs. |
| do-while loop | After execution (Post-test) | When the loop body must execute at least once (e.g., dynamic menus). |
Embedded Focus
Loops are heavily used in embedded systems because firmware applications must run continuously while monitoring registers, pins, and sensors.
while(1)
{
read_sensor(); // Microcontroller runs this code forever
}
In embedded software design, infinite loops keep the central microcontroller alive, running background operations, and responding to physical events continuously.