Loops in C (for, while, do-while)

Master loops in C programming: for loops, while loops, and do-while loops. Learn iteration mechanics, break and continue statements, and avoiding infinite loops.
Loops enable repetitive execution of code blocks based on boolean conditions. C provides three primary loop constructs: for loops, while loops, and do-while loops.
A for loop is ideal for counting and index-based iterations where initialization, condition, and increment expressions are bundled in a single line. A while loop tests its condition before executing the loop body, making it ideal for event loops and input reading.
A do-while loop is unique because it guarantees that the loop body executes at least once before the condition is evaluated at the bottom.
Interactive Runnable C Implementation
#include <stdio.h>
int main(void) {
printf("=== 1. For Loop with Break & Continue ===\n");
for (int i = 1; i <= 8; i++) {
if (i == 3) {
printf(" Skipping iteration i = %d (continue)\n", i);
continue;
}
if (i == 7) {
printf(" Terminating early at i = %d (break)\n", i);
break;
}
printf(" For index: %d\n", i);
}
printf("\n=== 2. While Loop (Bitwise Power Generator) ===\n");
int power = 1;
while (power <= 32) {
printf(" 2^k value = %d\n", power);
power *= 2;
}
printf("\n=== 3. Do-While Loop (Guaranteed 1+ Run) ===\n");
int count = 0;
do {
printf(" Executed do-while body (count = %d)\n", count);
count++;
} while (count < 2);
return 0;
}
Expected Output
=== 1. For Loop with Break & Continue ===
For index: 1
For index: 2
Skipping iteration i = 3 (continue)
For index: 4
For index: 5
For index: 6
Terminating early at i = 7 (break)
=== 2. While Loop (Bitwise Power Generator) ===
2^k value = 1
2^k value = 2
2^k value = 4
2^k value = 8
2^k value = 16
2^k value = 32
=== 3. Do-While Loop (Guaranteed 1+ Run) ===
Executed do-while body (count = 0)
Executed do-while body (count = 1)
Frequently Asked Questions
When should I use do-while over while?
Use do-while when an action must occur before validating conditions, such as prompting a user for valid input at least once.