C Loops (for, while) Tutorial
Loops in C programming allow you to execute a block of code multiple times efficiently. This tutorial covers for, while, and do-while loops.
1. The for Loop
The for loop is used when the number of iterations is known:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Iteration %d\\n", i);
}
return 0;
}
This loop runs 5 times, printing the current iteration.
2. The while Loop
The while loop executes as long as its condition is true:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("Iteration %d\\n", i);
i++;
}
return 0;
}
The while loop checks the condition before each iteration.
3. The do-while Loop
The do-while loop guarantees at least one execution of the loop body:
#include <stdio.h>
int main() {
int i = 0;
do {
printf("Iteration %d\\n", i);
i++;
} while (i < 5);
return 0;
}
The do-while loop evaluates the condition after each execution.
4. Nested Loops
Loops can be nested to perform more complex tasks:
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("i = %d, j = %d\\n", i, j);
}
}
return 0;
}
Nested loops execute one loop inside another.
5. Conclusion
Loops are fundamental for repetitive tasks in C. Practice using for, while, and do-while to master their usage.