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

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 "print 1 through 5" without one, and see how tedious programming would get.

❌ 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 is barely tolerable β€” but what if you had to print 1 through 100?
Imagine this: you're told to print 1 through 100. Would you really write printf("1\n"); printf("2\n"); ... printf("100\n"); for 100 lines? And if the spec changed to "multiples of 3 only," you'd have to rewrite the whole thing.

βœ… With a loop

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
Just three lines! Want to go up to 100? Change 5 to 100. Even 10,000 iterations fit in the same amount of code.

Feel the power of loops with this slider

Drag to change the iteration count and watch how many lines you'd need without a loop.
❌ Without loop
5 lines
One printf per iteration, N times
βœ… With loop
3 lines
Same code, whatever N is

It gets worse when the logic changes

Computing "the sum from 1 to 10" without a loop is just as 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 you write.
It gets even worse: if the iteration count 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 simply don't know how many printfs to write until the program actually runs.

for loop — a fixed number of iterations

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

πŸ” A for loop's (...) splits into three parts

In for ( A ; B ; C ), each of the three semicolon-separated sections has its own distinct job.
for (A: init ; B: condition ; C: update) { ... }
A: init (runs once at the start)
Runs once, before the loop begins. Usually declares the counter and sets its initial value.
Example: int i = 0
B: condition (checked before each iteration)
Checked at the top of every iteration. If true, the body runs; if false, the loop ends.
Example: i < 5
C: update (runs at the end of each iteration)
Runs after the body each time, usually to advance the counter (increment or decrement).
Example: i++
πŸ“‹ Execution-order trace (for (int i = 0; i < 3; i++) printf("%d ", i);)
β‘  A: i = 0 (runs once)
β‘‘ B: i < 3 ? β†’ true β†’ body: printf("0 ") β†’ C: i++ β†’ i=1
β‘’ B: i < 3 ? β†’ true β†’ body: printf("1 ") β†’ C: i++ β†’ i=2
β‘£ B: i < 3 ? β†’ true β†’ body: printf("2 ") β†’ C: i++ β†’ i=3
β‘€ B: i < 3 ? β†’ false β†’ loop ends (neither body nor C runs)
Output: 0 1 2
πŸ’‘ Any of the three parts can be omitted (but the meaning shifts)

🎨 Five common patterns

β‘  0 to N-1 (most common)
for (int i = 0; i < N; i++) { ... }
The standard array-index loop: 0, 1, …, N-1
β‘‘ 1 to N
for (int i = 1; i <= N; i++) { ... }
A math-style "count from 1" loop: 1, 2, …, N
β‘’ Countdown (i--)
for (int i = N; i >= 0; i--) { ... }
Counts down N, N-1, …, 1, 0 β€” handy for processing things in reverse.
β‘£ Skip (i += 2)
for (int i = 0; i < N; i += 2) { ... }
Even numbers only β€” step by two: 0, 2, 4, …
β‘€ Infinite loop (omit B or for (;;))
for (;;) {
  ...
  if (exit_condition) break;
}
Puts the exit condition inside the body via break β€” common for menu loops and event loops.

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 moves on to the next one. The loop itself keeps going.
for (int i=0; i<5; i++) {
    if (i == 2) continue;
    printf("%d ", i);
}
// Output: 0 1 3 4 (skips 2)
Watch out: break and continue only affect the innermost loop. A break inside a nested loop does not exit the outer one.

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

continue means "skip the rest of this iteration and move to the next one." Unlike break, the loop doesn't exit. Let's trace it 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++ still 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 ends the loop
πŸ’‘ Key point: after continue, the for's update clause i++ still runs. That's why i=2 is skipped but i=3 comes next.
πŸ”΄ Misconception β‘ : "continue is kind of like break, right?"
They're opposites. Swap one for the other and the behavior changes completely.
breakcontinue
Whole loopExits (done)Continues (next iteration)
Rest of this iterationSkippedSkipped
for's update i++Not runRuns
When to use"I'm done searching""skip just this element"
πŸ”΄ Misconception β‘‘: continue inside a while can cause an infinite loop
In a for loop, the counter update lives in the header β€” it always runs. 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 you continue:
if (i == 2) { i++; continue; }  // βœ… safe
πŸ’‘ continue vs. wrapping in an if β€” a readability trade-off
"Skip certain items" can be written with continue or with an if. Which reads better depends on the situation.
βœ… continue wins: the 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 flat and readable.
⚠️ The 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 make the if-nesting deep.
Rule of thumb:
β€’ One simple skip + short body β†’ use if
β€’ Multiple skips + long body β†’ use continue (guard-clause style)
It's the same idea as an early return in functions β€” see if Statement.

Try it yourself — loops

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

Related Lessons

Arrays & Strings
Lesson 20: 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. How many times does for (int i=10; i>0; i--) execute?

9 times
10 times
11 times

i takes the ten values 10, 9, 8, …, 1, so the body runs 10 times. The condition i > 0 means the body never runs when i=0.

Q3. What does for (;;) { ... } do?

Runs zero times
Infinite loop
Compile error

When all three parts (init / condition / update) are omitted, the missing condition is treated as always true, so the loop runs forever. Use break or return to exit.

Q4. What does this code print?

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

continue skips the rest of the current iteration and moves on. The printf is only skipped when i=3, so the output is 0 1 2 4.
With break, the loop would exit entirely at that point, giving 0 1 2 β€” don't confuse the two.

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