Loops (for, while, do-while)
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
A for loop has three parts separated by semicolons: initialization (int i = 0, runs once), condition (i < 5, checked before every iteration), and increment (i++, runs after every iteration). This makes it ideal when you know exactly how many times you want to repeat something.
int count = 0;
while (count < 3) {
printf("Attempt %d\n", count + 1);
count++;
}
A while loop checks its condition before each iteration, and keeps running as long as it stays true. Use it when the number of repetitions depends on something that isn't known in advance — like reading input until the user types "quit".
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while (num <= 0);
The key difference from a regular while loop: a do-while loop checks its condition after running the block, guaranteeing the code inside runs at least once — perfect for input validation, where you need to ask the user at least one time no matter what.
for (int i = 1; i <= 5; i++) {
if (i == 4) break; // exit the loop entirely
if (i == 2) continue; // skip this iteration, go to next i
printf("%d\n", i);
}
// Nested loop for a multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
Writing while (num = 0) instead of while (num == 0) is dangerous in C because it's not a syntax error — num = 0 is a valid assignment that evaluates to 0 (false), so the loop simply never runs, and no error message tells you why. Always double-check for double equals signs in every condition.
Print a simple multiplication table for the number 7, from 7×1 up to 7×10, using a for loop.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("7 x %d = %d\n", i, 7 * i);
}
return 0;
}