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

Lesson 10: Loops (for, while, do-while)

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

while loop

int n = 1;
while (n <= 100) {
  n = n * 2;
}
printf("n = %d\n", n); // -> 128
Caution: If the condition stays true forever, you get an infinite loop!

Step execution — for loop

for_demo.c

Variable state

NameTypeValue

Standard output

 

do-while — always runs at least once

while checks the condition before the body; do-while checks it after. As a result, the body of a do-while runs at least once.
while (pre-test)
while (condition) {
    body;  // 0 iterations if false
}
do-while (post-test)
do {
    body;  // runs at least once
} while (condition);
Watch the trailing semicolon! Forgetting the ; after } while (condition); is a compile error.

Typical use: re-prompt on invalid input

"Enter 1-3" → re-prompt on bad input. do-while is ideal here.
int choice;
do {
    printf("Pick 1-3> ");
    scanf("%d", &choice);
    if (choice < 1 || choice > 3)
        printf("Invalid input\n");
} while (choice < 1 || choice > 3);
printf("You picked %d\n", choice);

Which loop to use

ConstructTest timingMin iterationsWhen to use
forPre-test0Known number of iterations
whilePre-test0Unknown count, stop on condition
do-whilePost-test1Must run at least once (input validation, etc.)

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.

Try it yourself — loops

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

Related Lessons

Arrays & Strings
Lesson 11: Arrays
How to declare, initialize, and access arrays in C, with memory diagrams.
Conditionals
Lesson 9: else if & 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 13: else if & switch
Next lesson →
Lesson 15: 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.