1. The for Loop
The for loop is best used when you know exactly how many times you want to repeat a task. It keeps the initialization, condition, and increment all in one line.
#include <stdio.h>
int main() {
printf("Counting 1 to 5 with a for loop:\n");
// for(initialization; condition; increment)
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}Expected Output:
Counting 1 to 5 with a for loop:
1 2 3 4 52. The while Loop
The while loop is used when the number of iterations isn't known beforehand. It checks the condition before entering the loop. If the condition is false at the start, the code never runs.
#include <stdio.h>
int main() {
int count = 1;
printf("Counting with a while loop:\n");
while (count <= 5) {
printf("%d ", count);
count++; // Don't forget to update the variable!
}
printf("\n");
return 0;
}Expected Output:
Counting with a while loop:
1 2 3 4 53. The do-while Loop
The do-while loop is unique because it checks the condition after the code runs. This guarantees that the loop body will execute at least once, regardless of the condition.
#include <stdio.h>
int main() {
int num = 10;
printf("Executing a do-while loop:\n");
do {
printf("This will print even though 10 is not < 5\n");
} while (num < 5);
return 0;
}Expected Output:
Executing a do-while loop:
This will print even though 10 is not < 54. Loop Control: break and continue
Sometimes you need to change the behavior of a loop while it’s running.
break: Exits the loop immediately.continue: Skips the rest of the current iteration and jumps to the next one.
for (int i = 1; i <= 10; i++) {
if (i == 3) continue; // Skip 3
if (i == 7) break; // Stop completely at 7
printf("%d ", i); // Output: 1 2 4 5 6
}Expected Output:
1 2 4 5 6