Definition
📌 Loops
Loops let you repeat a block of code multiple times without rewriting it.
Syntax
syntax
for (init; condition; update) { }
while (condition) { }
do { } while (condition);Example
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}Output
output1 2 3 4 5
Important Points
breakexits a loop immediately;continueskips to the next iteration.- Use
forwhen the number of repetitions is known ahead of time. - Use
whilewhen the loop should keep running until some condition changes. - An incorrect loop condition can create an infinite loop — always double-check the update step.
Common Mistakes
- Forgetting to update the loop variable, causing an infinite loop.
- Off-by-one errors: using
<instead of<=(or vice versa). - Accidentally putting a semicolon right after the loop header:
for(...);.
Interview Tip
🎯 Before your interview
Interviewers love asking for the difference between
while and do-while — the key is that do-while guarantees at least one execution.
