C for Loop

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
Control flow

What You’ll Learn

The for loop is C’s go-to tool when you want to repeat code a known number of times—count from 0 to 9, walk every element of an array, or build a multiplication table with nested loops. This tutorial covers syntax, five worked examples, and pitfalls every beginner should avoid.

01

Syntax

init; test; update.

02

Counting

0 to n-1.

03

Arrays

Index walk.

04

Nested

Rows & cols.

05

break

Exit early.

06

Pitfalls

Off-by-one.

Definition and Usage

A for loop executes a block of code repeatedly while a condition is true. Unlike a while loop, which only has a condition, the for loop packs three steps into its header: set up a counter, test it, and update it after each pass.

Choose for when the number of iterations is clear before the loop runs—printing ten lines, summing an array, or drawing a pattern with row and column indices. The compact header keeps loop control visible in one place.

💡
Beginner Tip

Read the header left to right: start here (int i = 0), keep going while (i < n), then do this each time (i++). The body runs only when the condition is true.

📝 Syntax

General form of the C for loop:

C
for (initialization; condition; update) {
    // statements to repeat
}

Components

  • Initialization — runs once before the first test (e.g. int i = 0).
  • Condition — checked before each iteration; if false, the loop ends (e.g. i < 10).
  • Update — runs after each iteration (e.g. i++, i += 2).

Common patterns

  • for (int i = 0; i < n; i++) — count from 0 up to n - 1.
  • for (int i = n - 1; i >= 0; i--) — count down to 0.
  • for (size_t i = 0; i < len; i++) — array index with size_t.

Compile

C
gcc program.c -std=c11 -o program

⚡ Quick Reference

PatternExample
Count 0..4for (int i = 0; i < 5; i++)
Count 1..nfor (int i = 1; i <= n; i++)
Array lengthn = sizeof(a) / sizeof(a[0])
Exit loop earlybreak; inside body
Skip iterationcontinue; inside body
Init
int i = 0

Start value

Test
i < n

Keep going?

Update
i++

Next step

Infinite
for (;;)

Like while(1)

Examples Gallery

Compile with gcc example.c -std=c11 -o example. Each program demonstrates a core for loop pattern.

📚 Getting Started

The classic counting loop every C beginner writes first.

Example 1 — Print Numbers 0 to 4

The simplest for loop: initialize i, test i < 5, increment with i++.

C
#include <stdio.h>

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

How It Works

i starts at 0. Each iteration prints i, then adds 1. When i reaches 5, the condition i < 5 is false and the loop stops—so you get 0 through 4, not 5.

Example 2 — Sum Integers 1 to n

Accumulate a total inside the loop body.

C
#include <stdio.h>

int main(void) {
    int n = 10;
    int sum = 0;

    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("Sum 1..%d = %d\n", n, sum);
    return 0;
}

How It Works

Here the loop starts at 1 and uses <= so the last value included is n. sum += i adds each value to the running total.

📈 Practical Patterns

Arrays, nested loops, and early exit.

Example 3 — Iterate Over an Array

Walk every element using an index and sizeof to get the length.

C
#include <stdio.h>

int main(void) {
    int arr[] = {10, 20, 30, 40, 50};
    size_t n = sizeof(arr) / sizeof(arr[0]);
    size_t i;

    for (i = 0; i < n; i++) {
        printf("arr[%zu] = %d\n", i, arr[i]);
    }

    return 0;
}

How It Works

sizeof(arr) / sizeof(arr[0]) counts elements only when arr is a real array in this scope—not a function parameter that decayed to a pointer.

Example 4 — Nested for Loops

Two loops: outer controls rows, inner controls columns.

C
#include <stdio.h>

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

How It Works

For each value of i, the inner loop runs j from 1 to 3 completely. Nested loops power grids, matrices, and pattern printing in C.

Example 5 — Stop Early with break

Search an array and exit the loop when the target is found.

C
#include <stdio.h>

int main(void) {
    int nums[] = {4, 7, 2, 9, 5};
    int target = 9;
    size_t n = sizeof(nums) / sizeof(nums[0]);
    size_t i;
    int found_at = -1;

    for (i = 0; i < n; i++) {
        if (nums[i] == target) {
            found_at = (int)i;
            break;
        }
    }

    if (found_at >= 0) {
        printf("Found %d at index %d\n", target, found_at);
    } else {
        printf("Not found\n");
    }

    return 0;
}

How It Works

break jumps out of the innermost loop immediately. Without it, the loop would keep scanning even after finding the value.

🚀 Common Use Cases

  • Counting — repeat an action N times.
  • Array processing — sum, search, or transform elements by index.
  • Pattern printing — nested loops for stars, numbers, and alphabet triangles.
  • Tables and grids — rows and columns in 2D data.
  • Buffered I/O — process fixed-size chunks of data.
  • Retry limits — try an operation up to max attempts.

🧠 How the for Loop Works

1

Initialization

Run once: set i = 0 (or your start value).

Once
2

Test condition

If false, skip body and exit loop.

Before body
3

Run body

Execute statements inside { }.

Repeat
4

Update & loop back

Run i++, then go to step 2.

📝 Notes

  • Semicolons separate the three header parts even when one is empty: for (;;).
  • < vs <= changes whether you include the endpoint—watch off-by-one errors.
  • Missing update (e.g. forgetting i++) causes an infinite loop.
  • continue skips to the next iteration; break leaves the loop entirely.
  • Declare loop variables with C99+ (-std=c99) for cleaner scope.
  • Nested loops multiply work: 3 × 3 runs 9 inner iterations.

⚡ Optimization

Hoist invariant calculations out of the loop—compute sizeof(arr) / sizeof(arr[0]) once before the for, not on every iteration. Use size_t for indices when comparing with sizes. For very hot loops, avoid redundant function calls inside the body and prefer simple increment (i++) over heavier updates unless needed.

Conclusion

The C for loop combines setup, test, and update in one readable header. Master counting, array walks, and nested loops here, then compare with while and do-while for other repetition patterns.

Practice the examples above until for (int i = 0; i < n; i++) feels natural—it appears in almost every real C program.

💡 Best Practices

✅ Do

  • Use i < n for 0-based counts of length n
  • Compute array length once before the loop
  • Use meaningful names: row, col, index
  • Keep the loop body short; extract helpers if it grows
  • Use break when search succeeds

❌ Don’t

  • Forget the update step (i++)
  • Modify the loop bound inside the loop without care
  • Use sizeof on a pointer thinking it is an array
  • Nest many loops without tracking complexity
  • Use = instead of == in the condition

Key Takeaways

Knowledge Unlocked

Five things to remember about the C for loop

Your foundation for repetition in C programs.

5
Core concepts
🔢 02

0..n-1

Common range.

Count
🗃 03

arr[i]

Index walk.

Arrays
🔄 04

Nested

Rows × cols.

Patterns
05

Off-by-one

< vs <=.

Pitfall

❓ Frequently Asked Questions

A for loop repeats a block of code while a condition is true. It combines initialization, condition test, and update in one line: for (int i = 0; i < n; i++) { ... }. Use it when you know how many times to iterate or can express the stop condition clearly.
Initialization runs once before the loop (e.g. int i = 0). Condition is checked before each iteration; if false, the loop stops (e.g. i < 10). Update runs after each iteration (e.g. i++). Any part may be empty, but the semicolons are required.
Use for when the loop variable and stopping rule are tied together—counting, walking an array by index, or a fixed number of repetitions. Use while when you repeat until an external condition changes (e.g. reading until EOF) and there is no natural counter in the header.
Yes in C99 and later: for (int i = 0; i < n; i++). The variable exists only inside the loop body and its controlling for statement. Compile with -std=c99 or newer. In older C, declare i before the loop.
The condition never becomes false—often a missing or wrong update (i++ forgotten), comparing with the wrong operator, or using = instead of == in the condition. Always verify the loop variable moves toward making the condition false.
Compute length: size_t n = sizeof(arr) / sizeof(arr[0]); then for (size_t i = 0; i < n; i++) { use arr[i]; }. Never use sizeof on a pointer parameter—it gives pointer size, not array length.
Did you know?

The C for statement is equivalent to while with extra syntax sugar: initialization runs once, then the pattern is “test condition, run body, run update, repeat.” Writing for (;;) with an empty header creates an intentional infinite loop—the same idea as while (1).

Continue to the while Loop

Learn when to use while instead of for for open-ended repetition.

while loop tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful