Topic 46 of 100 Control Flow in C Interactive Tutorial

C for Loop: Syntax, Execution Steps, and Flowchart

12 mins read Last updated: 22 Aug 2026 28,100 views
C Compiler 0.00%

What is C for Loop? Core Concept & Direct Summary

Core Objective & Problem Statement

What is the internal execution cycle of a C `for` loop: initialization, condition, body, and increment expression?

Direct Answer Summary

Ask a working C programmer which loop they use most, and the answer is almost always the same: for. It's the counting specialist — the loop you reach for when you know (or can calculate) exactly how many times something should happen. Print ten lines, process thirty array elements, draw a pyramid of stars — that's for territory.

What makes it special is its design: everything that controls the loop lives in one header line, right where you can see it. No initialization hiding three lines above, no update buried at the bottom of the body. This tutorial takes that header apart piece by piece, walks through the exact execution order (it's not what most beginners assume), and finishes with the classic pattern programs that make for loops genuinely fun.

(Suggested image: THE hero graphic — the for-loop flowchart: Initialization → Condition? → (true) Body → Update → back to Condition / (false) Exit. This exact flowchart is a top image-search result for this topic.)

How Does C for Loop Work? In-Depth Mechanics & Architecture

The Syntax, Labeled

main.c
Run Online
for (initialization;
condition;
update) {
    // loop body
}

Three expressions inside the parentheses, separated by semicolons (not commas — a classic typo):

PartPurposeRuns How Often
initializationSets up the loop counterExactly once, at the start
conditionDecides whether to continueBefore every iteration
updateMoves the counter forwardAfter every iteration
bodyThe work being repeatedOnce per iteration

A concrete example to hold onto:

main.c
Run Online
for (int i = 1;
i <= 5;
i++) {
    printf("%d ", i);
}
// Output: 1 2 3 4 5

The Exact Execution Order (Step by Step)

Most beginners assume the loop just reads left to right. It doesn't. Here's the actual sequence C follows:

Architecture Diagram
1. initialization        → i = 1           (once, ever)2. condition check       → is i <= 5?     ├─ false → EXIT the loop     └─ true  → continue3. body                  → print i4. update                → i++5. back to step 2

Watch it play out with for (int i = 1; i <= 3; i++):

StepActioniOutput
Initi = 11
Check1 <= 3? ✓1
Bodyprint11
Updatei++2
Check2 <= 3? ✓2
Bodyprint22
Updatei++3
Check3 <= 3? ✓3
Bodyprint33
Updatei++4
Check4 <= 3? ✗—EXIT

Two details worth memorizing from that table:

  • The condition is checked BEFORE the body — so if it's false immediately, the body never runs (zero iterations is perfectly legal)
  • The update runs AFTER the body, not before — that's why i = 1 gets printed on the first pass

(Suggested image: this trace table as an infographic — "anatomy of 3 iterations" — highly shareable for students)


First Programs: Counting Both Ways

Counting up:

main.c
Run Online
for (int i = 1;
i <= 10;
i++) {
    printf("%d ", i);
}
// 1 2 3 4 5 6 7 8 9 10

Counting down (flip the condition, flip the update):

main.c
Run Online
for (int i = 10;
i >= 1;
i--) {
    printf("%d ", i);
}
puts("Blast off!");
// 10 9 8 7 6 5 4 3 2 1 Blast off!

Custom steps — the update doesn't have to be ++:

main.c
Run Online
for (int i = 0;
i <= 20;
i += 2) {
    printf("%d ", i);
}
// 0 2 4 6 8 10 12 14 16 18 20

The classic — sum of first N natural numbers:

main.c
Run Online
#include <stdio.h>
int main() {
    int n, sum = 0;
    printf("Enter n: ");
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    printf("Sum of 1 to %d = %d\n", n, sum);
    return 0;
}

Sample Run:

main.c
Run Online
Enter n: 100Sum of 1 to 100 = 5050

The Header Is Flexible: Variations You Should Recognize

The three header slots are more permissive than they look. All of these are legal:

Declare the counter outside (needed if you use it after the loop):

main.c
Run Online
int i;
for (i = 1;
i <= 5;
i++) {
    printf("%d ", i);
}
printf("\nStopped at i = %d\n", i);
// i survives here — prints 6

Multiple variables with commas:

main.c
Run Online
for (int i = 1, j = 10;
i < j;
i++, j--) {
    printf("i=%d j=%d\n", i, j);
}
// i=1 j=10// i=2 j=9// ... until they cross

Omit any part (the semicolons must stay!):

main.c
Run Online
int i = 1;
for (;
i <= 5;
i++) {
}
// init outside
for (int k = 1;
k <= 5;) {
    // update inside body    printf("%d ", k);
    k++;
}

Omit everything — the intentional infinite loop:

main.c
Run Online
for (;;) {
    // runs forever — needs a break inside    printf("Press 0 to quit: ");
    int choice;
    scanf("%d", &choice);
    if (choice == 0) break;
}

Watch out: for (;;) is a deliberate infinite loop, same as while (1). Omitting the condition doesn't mean "no condition" — C treats a missing condition as always true.


Nested for Loops: Grids and Patterns

Put a for inside a for, and the inner loop runs completely for every single pass of the outer one. This is how you work in two dimensions:

main.c
Run Online
for (int row = 1;
row <= 3;
row++) {
    for (int col = 1;
    col <= 5;
    col++) {
        printf("* ");
    }
    printf("\n");
    // new line after each row
}

Output:

3 rows × 5 columns = 15 stars. The outer loop controls rows, the inner loop controls columns, and the newline sits between them. This outer/inner rhythm is the skeleton of every pattern program.

(Suggested image: a visual showing the grid with row numbers on the left, column numbers on top, and arrows marking which loop controls which dimension)


The Classic Pattern Programs

Every C course assigns these, and for good reason — they're the fastest way to build loop intuition. The trick is always the same: find the formula connecting row number to inner-loop count.

Right triangle:

main.c
Run Online
for (int i = 1;
i <= 5;
i++) {
    for (int j = 1;
    j <= i;
    j++) {
        // inner count = row number!        printf("* ");
    }
    printf("\n");
}

Number triangle:

main.c
Run Online
for (int i = 1;
i <= 4;
i++) {
    for (int j = 1;
    j <= i;
    j++) {
        printf("%d ", j);
    }
    printf("\n");
}

Pyramid (the famous one) — two inner loops: spaces, then stars:

main.c
Run Online
int n = 5;
for (int i = 1;
i <= n;
i++) {
    for (int s = 1;
    s <= n - i;
    s++) {
        // spaces shrink        printf(" ");
    }
    for (int j = 1;
    j <= 2 * i - 1;
    j++) {
        // stars grow: 1, 3, 5, 7...        printf("*");
    }
    printf("\n");
}
main.c
Run Online
* *** ***** ****************

Don't memorize these — derive them. Ask: "in row i, how many spaces? how many stars?" The formulas (n - i, 2*i - 1) fall out of that question every time.


for vs while: When the Counter Wins

Since any loop can imitate any other, here's the honest comparison:

SituationBetter Choice
Counted repetitions (1 to N)for
Loop until a condition changeswhile
Must run at least oncedo-while
Array/table processingfor
Input validation (unknown attempts)while / do-while

The for loop's killer feature isn't power — it's locality. Initialization, condition, and update sit on one line, so the entire "story" of the loop is visible at a glance. Nobody has to scroll to find where the counter changes.


The Six Classic for-Loop Mistakes

1. The stray semicolon (the all-time champion):

main.c
Run Online
for (int i = 1;
i <= 5;
i++);
// ← semicolon = empty body!{
printf("%d\n", i);
// runs ONCE, after the loop: prints 6
}

2. Off-by-one:

main.c
Run Online
for (int i = 1;
i < 5;
i++) // prints 1 2 3 4 — NOT 1 2 3 4 5

< 5 stops at 5; <= 5 includes 5. When your loop count is wrong by exactly one, the comparison operator did it.

3. Wrong update direction:

main.c
Run Online
for (int i = 10;
i >= 1;
i++) // i grows AWAY from 1 — infinite loop!

4. Comma instead of semicolon in the header:

main.c
Run Online
for (int i = 0, i < 5, i++) // ✗ compile error — semicolons only

5. Modifying the counter inside the body:

main.c
Run Online
for (int i = 1; i <= 10; i++) {
    i += 2;
    // legal, but the loop now skips unpredictably
}

6. Looping with float counters:

main.c
Run Online
for (float f = 0.0f;
f != 1.0f;
f += 0.1f) // 0.1 isn't exact in binary...

Floating-point rounding means f may never hit exactly 1.0 — infinite loop. Use integer counters; compute floats inside the body if needed.

(Suggested image: "6 for-loop Mistakes" checklist graphic, consistent with the series)


A Complete Example: Prime Number Checker

main.c
Run Online
#include <stdio.h>
int main() {
    int num, isPrime = 1;
    printf("Enter a number: ");
    scanf("%d", &num);
    if (num < 2) {
        isPrime = 0;
    } else {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
                // found a divisor — no point checking further
            }
        }
    }
    if (isPrime) {
        printf("%d is prime.\n", num);
    } else {
        printf("%d is not prime.\n", num);
    }
    return 0;
}

Sample Runs:

main.c
Run Online
Enter a number: 29
29 is prime.
main.c
Run Online
Enter a number: 30
30 is not prime.

Notice the loop design: we only check divisors up to num / 2 (no larger divisor can possibly divide evenly), and break exits the instant we find one. That's the for loop used thoughtfully — counted repetition with an early escape.


Final Thoughts

The for loop earns its popularity through sheer clarity: one header line tells you where the loop starts, when it stops, and how it moves. Master the execution order — init once, check before, body, update after — and every for loop you'll ever read becomes transparent.

Practice priority: counting both directions, the sum program, then the star patterns until you can derive them from the "how many in row i?" question. Do that, and nested loops stop being scary — they become a tool you genuinely enjoy.

Next in the cluster: the while loop, where we drop the counter and let a condition run the show.

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        sum += i;
    }
    printf("Sum of numbers 1 to 10 is: %d\
", sum);
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Declare loop index variables locally in the loop header (for (int i = 0; ...)) to avoid index variable leakage into surrounding scope.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: What is the scope of a variable declared inside a `for` loop header `for (int i = 0; ...)`?

A: Its scope is restricted strictly to the `for` loop block (introduced in C99); it does not exist after the loop terminates.
Q

Q: What is the output of `for (int i = 0; i < 5; ++i)` vs `i++`?

A: Identical! The update expression is evaluated as an isolated statement after the body finishes.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations