A loop repeats a block of code. Printing 1 to 100, adding the marks of 60 students, or reading lines until the user types "exit" - all of these are loops.
The for loop#
Use for when you know how many times to repeat.
for (initialisation; condition; update) {
// body
}
- initialisation runs once (
int i = 1). - condition is checked before every iteration; if false, the loop ends.
- The body runs.
- update runs (
i++), then back to step 2.
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
Counting down and stepping by more than 1:
10 8 6 4 2 0 Lift-off!
The while loop#
Use while when you do not know in advance how many repetitions are needed - you loop while a condition holds.
Reversed: 4321
n % 10 से आखिरी अंक मिलता है और n / 10 से आखिरी अंक हट जाता है। यह trick (अंक निकालना) digits का sum, reverse number, palindrome, Armstrong number जैसे बहुत सारे interview सवालों में काम आती है।
The do-while loop#
The body runs first, then the condition is checked - so it always runs at least once. It is ideal for menus and input validation.
Wrong PIN (1111) Unlocked after 2 tries
break and continue#
break- leave the loop immediately.continue- skip the rest of this iteration and go to the next.
1 2 4 5 7
Nested loops and patterns#
A loop inside a loop. The inner loop completes all its iterations for each iteration of the outer loop. Pattern questions are very common in exams:
* *** ***** ******* *********
For row i there are n - i spaces and 2i - 1 stars. Work out the formula for each part of a pattern first, then write the loops.
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16
Infinite loops#
for (;;) and while (1) loop forever - useful in servers and embedded code, with a break inside to exit. An accidental infinite loop usually means the update is missing or wrong:
int i = 0;
while (i < 5) {
printf("%d", i);
// forgot i++ → runs forever
}
If your program "hangs" with no output, look for a loop whose condition never becomes false. The online compiler stops programs that run too long.
Which loop should I use?#
| Loop | Best when | Checks condition |
|---|---|---|
for |
the number of repetitions is known | before each iteration |
while |
repeat until something happens | before each iteration |
do-while |
the body must run at least once (menus) | after each iteration |
Summary#
for (init; cond; update)for counted loops;whilefor condition-based loops;do-whileruns at least once.breakexits a loop,continueskips to the next iteration.- Nested loops print patterns and grids: outer loop = rows, inner loop = columns.