Loops in C allow programmers to execute a block of code multiple times based on a condition. Loops are essential for automation, iterating through data, and handling repetitive tasks efficiently. In this tutorial, we will explore the different types of loops in C and how to use them effectively.
C provides three main types of loops:
The for loop has a fixed number of iterations:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
The while loop runs as long as the condition is true:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}
The do-while loop executes at least once before checking the condition:
#include <stdio.h>
int main() {
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
} while (i < 5);
return 0;
}
Break: Exits the loop immediately.
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
printf("Iteration %d\n", i);
}
Continue: Skips the current iteration and continues with the next.
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
printf("Iteration %d\n", i);
}
Loops can be nested inside each other:
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Practice using loops by:
For further learning, visit the C Programming Tutorial.