Looping Statements (Repetition)
Loops allow you to repeat a set of instructions multiple times until a condition is false.
🔹 for Loop
Best used when the number of iterations is known.
for (int i = 1; i <= 5; i++) {
printf(“%d “, i);
}
Output: 1 2 3 4 5
🔹 while Loop
Condition is checked before entering the loop. Used when the number of iterations is unknown.
int i = 1;
while (i <= 5) {
printf(“%d “, i);
i++;
}
🔹 do-while Loop
The block is executed at least once, even if the condition is false.
int i = 1;
do {
printf(“%d “, i);
i++;
} while (i <= 5);
🔹 Comparison Table for Loops
|
Loop Type |
Condition Check |
Executes At Least Once |
When to Use |
|
for |
Before loop |
|
When loop count is known |
|
while |
Before loop |
|
When loop count is unknown |
|
do-while |
After loop |
|
When the loop must run once |
Jumping Statements (Transfer of Control)
These statements are used to change the flow within loops or switch blocks.
|
Statement |
Use |
|
break |
Exits from loop or switch immediately |
|
continue |
Skips current iteration, continues loop |
|
goto |
Jumps to a labeled statement (avoid unless necessary) |
Example with continue:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf(“%d “, i);
}
Output: 1 2 4 5 — Skips printing 3
Example with break:
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
printf(“%d “, i);
}
Output: 1 2 — Exits loop when i = 3