C Loops
The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops.
1. For Loop
Why use loops in C language?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition check, and increment/decrement operation.
Syntax:
for (initialization; condition; increment/decrement)
{
// code to be executed
}
Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
4
2. While Loop
The while loop is used when you want to repeat a block of code an indefinite number of times until a condition is false. The condition is checked before each iteration.
Syntax:
while (condition) {
// code to be executed
}
Example:
#include <stdio.h>
int main()
{
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
3. Do-While Loop
The do-while loop is similar to the while loop, but the condition is checked after the loop executes, ensuring the block of code runs at least once.
Syntax:
do {
// code to be executed
} while (condition);
Example:
#include <stdio.h>
int main()
{
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
return 0;
}
Output:
1
2
3
4
4. Key Differences
Feature | For Loop | While Loop | Do-While Loop |
---|---|---|---|
Condition Check | At the beginning of each iteration | At the beginning of each iteration | At the end of each iteration |
Minimum Iterations | Zero or more | Zero or more | At least one |
Use Case | When the number of iterations is known | When the number of iterations is unknown, condition checked before each iteration | When the block must execute at least once, condition checked after each iteration |
5. When to Use
- Use for loop when the number of iterations is fixed or known.
- Use while loop when you want to repeat a block of code while a condition is true, but the number of iterations is not known.
- Use do-while loop when the code should execute at least once regardless of the condition.