</>
ShikshaCSLearn. Code. Grow.
🔍
☕ Support Us
ShikshaCSNotesProgramming in C
Programming in C
🕒 7 min read

Loops (for, while, do-while)

Repeating actions without writing the same code again and again.

for Loop

Used when you know how many times to repeat in advance. It combines initialization, condition, and increment/decrement in one line, making it compact and readable for counting loops.

for (int i = 1; i <= 5; i++) {
  printf("%d ", i);
} // prints 1 2 3 4 5

while Loop

Checks the condition BEFORE each iteration — useful when the number of repetitions isn't known in advance, like reading input until the user types 'quit'.

int n = 5;
while (n > 0) {
  printf("%d ", n);
  n--;
}

do-while Loop

Checks the condition AFTER each iteration, so the loop body always runs at least once — useful for menu-driven programs where you want to show the menu at least one time before checking whether to continue.

🌍 Real-World Use

Any repeated task — printing a multiplication table, processing every item in a shopping cart, or running a game loop that keeps checking for player input — relies on loops.

💡 Pro Tip

A classic bug is the 'infinite loop' — forgetting to update the loop variable (like forgetting n-- in a while loop) causes the condition to never become false. Always double-check your loop actually moves toward its exit condition.

🧪 Quick Self-Test

Check what you just learned — no pressure, just practice.

1. Which loop guarantees the body runs at least once?

2. What causes an infinite loop?

← Back to all Notes