Loop Constructs
Loops repeat code blocks. C provides three loop types: for (known count), while (condition-based), and do-while (runs at least once). Combined with break and continue, they handle all iteration patterns.
35 min•By Priygop Team•Last updated: Feb 2026
Loop Examples
Example
#include <stdio.h>
int main() {
// for loop
for (int i = 0; i < 10; i++) {
printf("%d ", i); // 0 1 2 3 4 5 6 7 8 9
}
printf("\n");
// while loop (condition checked first)
int count = 0;
while (count < 5) {
printf("Count: %d\n", count);
count++;
}
// do-while (runs at least once)
int input;
do {
printf("Enter positive number: ");
scanf("%d", &input);
} while (input <= 0); // Keeps asking until valid
// break: exit loop early
for (int i = 0; i < 100; i++) {
if (i == 42) break; // Exit at 42
printf("%d ", i);
}
// continue: skip to next iteration
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // Skip even numbers
printf("%d ", i); // 1 3 5 7 9
}
// Nested loops: multiplication table
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= 5; col++) {
printf("%4d", row * col);
}
printf("\n");
}
// Practical: find prime numbers
for (int num = 2; num <= 50; num++) {
int isPrime = 1;
for (int div = 2; div * div <= num; div++) {
if (num % div == 0) {
isPrime = 0;
break;
}
}
if (isPrime) printf("%d ", num);
}
return 0;
}