Looping in C allows a set of instructions to be executed repeatedly based on a condition. This is useful for tasks that require repetitive execution, such as iterating over an array or performing calculations multiple times.
Types of Loops in C
C provides three types of loops:
forLoopwhileLoopdo-whileLoop
1. for Loop
The for loop is used when the number of iterations is known beforehand.
Syntax:
- Initialization: Sets the starting point of the loop.
- Condition: Determines whether the loop should continue.
- Increment/Decrement: Updates the loop control variable.
Example: Printing Numbers 1 to 5
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf(“%d\n”, i);
}
return 0;
}
Output:
1
2
3
4
5
2. while Loop
The while loop is used when the number of iterations is not known beforehand, and it continues until the condition becomes false.
Syntax:
Example: Printing Numbers 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf(“%d\n”, i);
i++; // Increment the counter
}
return 0;
}
Output:
1
2
3
4
5
3. do-while Loop
The do-while loop is similar to the while loop but guarantees that the code inside the loop is executed at least once, regardless of the condition.
Syntax:
Example: Printing Numbers 1 to 5
#include <stdio.h>
int main() {
int i = 1;
do {
printf(“%d\n”, i);
i++; // Increment the counter
} while (i <= 5);
return 0;
}
Output:
1
2
3
4
5
Comparison of Loops
| Type of Loop | When to Use | Condition Check |
|---|---|---|
for Loop |
When the number of iterations is known beforehand. | Before each iteration. |
while Loop |
When the number of iterations is not fixed and depends on a condition. | Before each iteration. |
do-while Loop |
When the loop must execute at least once, regardless of the condition. | After each iteration. |
Special Statements in Loops:
break:- Exits the loop immediately.
- Example:
Output:
continue:- Skips the rest of the code in the current iteration and moves to the next iteration.
- Example:
Output:
