HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to CVariablesData TypesOperatorsStringsArraysConditions (if / switch)Loops (for / while)FunctionsPointers
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🔁 Condition & Loop
🧩 Function
👉 Pointer
C›Loops (for / while)

Loops (for / while)

Definite repetition with for and conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
#include <stdio.h>
2
int main() {
3
for (int i = 1; i <= 3; i++) {
Initialization; condition; increment.
LoopInitialization; condition; increment.
4
printf("%d\n", i);
1, 2, 3
Output / Input1, 2, 3
5
}
6
return 0;
7
}
LoopOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

C has three loop structures: for, while, and do-while. The difference between them is not functional but syntactic. The for loop consolidates counter management into a single line; while is condition-focused; do-while executes the body at least once.

The for loop in C is more general than its counterparts in other languages. None of the three parts are mandatory, and you can write any expression you like. Leaving all three parts empty produces an infinite loop, and this pattern is intentionally used in embedded systems.

The most common mistake in loops is boundary calculation. Since the last index in an array is one less than the number of elements, writing less-than-or-equal overflows the array by one element. Since C does not perform bounds checking, this error appears not as a crash, but as a silent memory read.

What you will learn

  • The difference between for, while, and do-while
  • How boundary errors occur
  • Using break and continue
  • How infinite loops occur and how they are intentionally written

When to use?

Use for when the number of iterations is known in advance, and while when it is not. Situations like file reading or waiting for user input are written with while because it is not known beforehand how many steps it will take.

In embedded systems, the main program is typically an infinite loop: it reads sensors and responds until the device is turned off.

Common mistakes

Wrong

#include <stdio.h>

int main() {
    int i = 0;
    while (i < 5) {
        printf("%d\n", i);
    }
    return 0;
}

Because the counter is never incremented, the condition never becomes false and the loop goes on infinitely. The program doesn't stop and keeps printing zero to the screen. Forgetting to write the increment operation inside the body when using while is the most common mistake; in for, this part is written separately so it is not forgotten.

Correct

#include <stdio.h>

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

Wrong

#include <stdio.h>

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

The semicolon at the end of the for line makes the loop body empty: the loop does nothing five times. The block below runs once independently of the loop, and since i is not defined there, it gives a compilation error. A semicolon is not placed after the loop header.

Correct

#include <stdio.h>

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

Wrong

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    int i = 0;
    while (i < 5) {
        if (numbers[i] == 3) {
            continue;
        }
        printf("%d\n", numbers[i]);
        i++;
    }
    return 0;
}

continue skips the increment line and returns to the condition. When the third element is reached, the counter is not incremented again and the loop enters an infinite loop. Since the increment part in a for loop is not affected by continue, this error does not occur; when jumping with while, the counter must be incremented beforehand.

Correct

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++) {
        if (numbers[i] == 3) {
            continue;
        }
        printf("%d\n", numbers[i]);
    }
    return 0;
}

Frequently asked questions

When is do-while necessary?

When the body needs to run at least once. A classic example is asking the user for valid input: you ask first, then check if it's valid. If you write it with while, you have to do the check before asking.

Can I break out of a nested loop with a single break?

No, break only breaks the loop it is inside. To break out of two loops at once, you can use a flag variable, move the operation to a function and return, or use goto. Moving it to a function is the most readable solution.

Is an infinite loop an error?

Not if it's intentional. In embedded systems and server programs, the main loop is infinite and is exited via break or return. The error is when the exit condition is never met: usually forgetting to increment the counter or incrementing it in the wrong direction.

Summary

for is counter-focused, while is condition-focused, and do-while executes the body at least once.

In an array loop, the condition must be less than the number of elements, not less-than-or-equal.

When using continue inside a while loop, increment the counter beforehand.

Putting a semicolon after the loop header empties the body.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code