πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English
Advertisement

Lesson 11: for Loop

Learn how to use for and while loops in C with step-by-step visual examples.

πŸ“– What to learn on this page
βœ… Must-know essentials
  • for (init; cond; update) { ... }
  • while (cond) { ... } runs while cond is true
  • break exits; continue skips to next iteration
⭐ Read if you have time
  • do-while runs at least once
  • Infinite loops: for (;;) / while (1)
  • Nested loops and complexity

Why Do We Need Loops? β€” The Pain of Repetition

What if loops didn't exist? Let's try writing "print 1 to 5" without any loop, and see how painful programming would be.

❌ Without loops

#include <stdio.h>

int main(void) {
    printf("1\n");
    printf("2\n");
    printf("3\n");
    printf("4\n");
    printf("5\n");
    return 0;
}
Five times is barely manageable, but… what if you needed to print 1 to 100?
Imagine this: You're told to print 1 to 100. Would you really write printf("1\n"); printf("2\n"); ... printf("100\n"); for 100 lines? And if the requirement changed to "print only multiples of 3", you'd have to rewrite everything.

βœ… With a loop

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
Just 3 lines! And if you want to go up to 100, just change 5 to 100. Even 10,000 iterations fit in the same amount of code.

Feel the power of loops with this slider

Change the number of iterations. See how many lines you'd need without a loop.
❌ Without loop
5 lines
You need to write printf N times
βœ… With loop
3 lines
Same code no matter what N is

It gets worse: what if the logic changes?

Computing "the sum of 1 to 10" without a loop is also painful.
// Without loop: manually add each number
int sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;

// With loop
int sum = 0;
for (int i = 1; i <= 10; i++) sum += i;
The essence of loops: "Repeat the same pattern, with a slightly different value each time." It's one of the most important concepts in programming β€” you'll see it in almost every program.
Even worse: If the number of iterations depends on user input (e.g., "sum from 1 to N where N is entered at runtime"), you can't write it without a loop. You don't know how many printf to write until the program runs.

for loop — a fixed number of iterations

for (int i = 0; i < 5; i++) {
  printf("i = %d\n", i);
}

Iteration-count visualizer

Current i
Iterations
0

Step execution — for loop

for_demo.c

Variable state

NameTypeValue

Standard output

 

break & continue — loop control

break
Exits the loop immediately. All remaining iterations are skipped.
for (int i=0; i<10; i++) {
    if (i == 5) break;
    printf("%d ", i);
}
// Output: 0 1 2 3 4
continue
Skips the rest of the current iteration and goes on to the next one. The loop itself keeps running.
for (int i=0; i<5; i++) {
    if (i == 2) continue;
    printf("%d ", i);
}
// Output: 0 1 3 4 (skips 2)
Caution: break and continue only affect the innermost loop. break inside a nested loop does not exit the outer loop.

πŸ” continue in depth β€” behaviour, misconceptions, readability

continue means "skip the rest of this iteration, go to the next one". Unlike break, the loop does not exit. Let's trace the execution step by step.
πŸ“‹ continue execution trace
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;    // ← when i==2, skip the rest
    printf("%d ", i);     // not reached after continue
}
Iteration 1 (i=0): i==2 false β†’ printf β†’ prints 0 β†’ i++ makes i=1
Iteration 2 (i=1): i==2 false β†’ printf β†’ prints 1 β†’ i++ makes i=2
Iteration 3 (i=2): i==2 true β†’ continue β†’ printf skipped β†’ i++ makes i=3 (key point)
Iteration 4 (i=3): i==2 false β†’ printf β†’ prints 3
Iteration 5 (i=4): i==2 false β†’ printf β†’ prints 4 β†’ i=5 terminates
πŸ’‘ Key point: after continue, the for's update clause i++ is still executed. That's why i=2 skipped but i=3 follows.
πŸ”΄ Misconception β‘  "continue is like break, right?"
They're opposites. Mixing them up changes behaviour completely.
breakcontinue
Whole loopExit (done)Continue (next iteration)
Rest of this iterationSkipSkip
for's update i++Not executedExecuted
When to use"done searching""skip just this element"
πŸ”΄ Misconception β‘‘ continue in a while can cause an infinite loop
for loops update the counter in the header β€” it always runs. But in a while loop you update the counter yourself inside the body, and continue can skip it. That's a classic infinite-loop trap.
int i = 0;
while (i < 5) {
    if (i == 2) continue;  // ❌ never reaches i++ β†’ stuck at i=2 forever
    printf("%d ", i);
    i++;
}
Fix: bump the counter before continuing:
if (i == 2) { i++; continue; }  // βœ… safe
πŸ’‘ continue vs wrapping in an if β€” readability trade-off
"Skip certain items" can be written with continue or with an if. Which reads better depends on the situation.
βœ… continue wins: early skip pattern
for (int i=0; i<n; i++) {
    if (arr[i] < 0) continue;  // skip negatives
    if (arr[i] == 0) continue; // skip zeros too

    // long main processing for positives...
    process(arr[i]);
    total += arr[i] * 2;
}
Filtering out unwanted cases up front keeps the main block un-indented.
⚠️ Same thing with if gets nested
for (int i=0; i<n; i++) {
    if (arr[i] > 0) {  // invert & wrap
        process(arr[i]);
        total += arr[i] * 2;
    }
}
One simple condition is fine. Multiple skip conditions β†’ if-nesting becomes deep.
Rule of thumb:
β€’ 1 simple skip + short body β†’ if
β€’ Multiple skips + long body β†’ continue (guard-clause style)
Same idea as early return in functions β€” see if Statement.

Try it yourself — loops

my_loop.c
Output
Click "Run" to execute...
πŸ’‘ Try these ideas too
Advertisement

Related Lessons

Arrays & Strings
Lesson 13: Arrays
How to declare, initialize, and access arrays in C, with memory diagrams.
Conditionals
Lesson 10: switch
Learn C else if and switch statements for multi-way branching.
Reference
C Cheat Sheet
Quick reference for printf, operators, types, and more.
← Previous lesson
Lesson 15: switch
Next lesson →
Lesson 17: Debugging

Review Quiz

Check your understanding of this lesson!

Q1. How many times does for (int i=0; i<5; i++) execute?

4 times
5 times
6 times

i takes the five values 0, 1, 2, 3, 4, so the body runs 5 times.

Q2. What happens with while(1)?

Runs exactly once
Infinite loop
Compile error

The condition is always 1 (true), so the loop keeps running forever unless broken out of by break or return.

Q3. What is the difference between do-while and while?

No difference
do-while runs at least once
do-while is faster

do-while tests the condition at the end of the loop, so the body always runs at least once. while tests first, so it can run zero times.

Share this article
Share on X (Twitter) Share on Facebook Send on LINE Hatena

Recommended Books to Deepen Your Understanding

Combine this interactive site with books for more practice.

πŸ“˜
Painfully Learning C
by MMGames
A classic C book for beginners. Builds solid fundamentals with clear explanations.
View on Amazon
πŸ“—
New Clear C Language (Beginner)
by Bohyoh Shibata
Plenty of diagrams and exercises. Widely used as a university textbook.
View on Amazon
πŸ“™
The C Programming Language, 2nd Ed.
by Brian Kernighan & Dennis Ritchie
Known as K&R. The original C book. Ideal after completing the basics.
View on Amazon

* Links above are affiliate links. Purchases help support this site.