C for Loop

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is a for Loop?

A for loop is C’s compact counted loop. The header holds init, condition, and update so the body’s job stays clear. Prefer it for fixed counts and index walks; use while when the stop rule is not a natural counter.

Remember
for (init; condition; update) {
    /* body */
}

init      → once, before the loop
condition → before each pass (false → stop)
update    → after each pass

for (int i = 0; i < n; i++)
semicolons in the header are required
UsePrefer
Counted / index-based workfor
Stop on input / external eventwhile
Must run body once firstdo-while

How to Use for in C

Fill the three header slots, write a small body, and keep the update moving toward the stop condition.

  1. Initialize the loop variable (often int i = 0 in C99+).
  2. Write a clear condition (e.g. i < n).
  3. Update after each pass (usually i++).
  4. Compile with gcc file.c -std=c11 -o out and run.
PieceRequired?Role
InitUsuallyRuns once before the first test
ConditionYes (to stop)Checked before each body run
UpdateUsuallyRuns after each body run

Pseudocode

Pseudocode
init loop variable

while condition is true:
    run the body
    run update

// empty condition means "always true"
// — then you must break yourself

Cheat Sheet

Keep these facts handy while writing counted loops.

TopicDetail
Syntaxfor (init; cond; update) { ... }
Test timingBefore the body (pre-test)
Minimum runs0 (if condition starts false)
C99 scopefor (int i = 0; ...) scopes i to the loop
Array lengthsizeof(a) / sizeof(a[0]) (real arrays only)
Exit earlybreak / continue
Off-by-onePrefer i < n for indexes 0 … n-1

Live Preview

Trace a small for header in the browser. Same control flow as the C examples below.

Browser simulation of for control flow (same idea as the C examples).

Result
for (i = 0; i < 3; i++) print i

init: i = 0
pass 1: 0 < 3 → print 0 → i = 1
pass 2: 1 < 3 → print 1 → i = 2
pass 3: 2 < 3 → print 2 → i = 3
test: 3 < 3 → false → stop

output: 0 1 2

Worked Walkthrough — i from 0 to 2

Follow for (int i = 0; i < 3; i++) printf("%d ", i); one phase at a time.

Calculation
init:      i = 0

1) test 0 < 3 → true
   body: print 0
   update: i = 1

2) test 1 < 3 → true
   body: print 1
   update: i = 2

3) test 2 < 3 → true
   body: print 2
   update: i = 3

4) test 3 < 3 → false → exit

output: 0 1 2
Using i <= 3 would print one extra value (off-by-one).

C Examples

Compile with gcc file.c -std=c11 -o out. Compare with while and do-while when choosing a style.

Example 1 — Print Numbers 0 to 4

The classic header: start at 0, stop before 5, add 1 each time.

C
#include <stdio.h>

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

How It Works

  1. Init once. i starts at 0 (C99 loop scope).
  2. Test before the body. Continue while i < 5.
  3. Print then update. After each print, i++ runs.
  4. Stop at 5. When i becomes 5, the condition fails and the loop ends.

Example 2 — Sum Integers 1 to n

Accumulate a total inside the body. The header still owns the counter.

C
#include <stdio.h>

int main(void) {
    int n = 5;
    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

  1. Start sum at 0. The accumulator lives outside the header.
  2. Count from 1 to n. i <= n includes both ends for 1-based totals.
  3. Add each value. sum += i folds 1+2+3+4+5.
  4. Result 15. Same as the formula n*(n+1)/2 for this small case.

Example 3 — Iterate Over an Array

Walk every element by index. Length comes from sizeof on a real array (not a pointer).

C
#include <stdio.h>

int main(void) {
    int scores[] = { 90, 85, 100 };
    size_t n = sizeof(scores) / sizeof(scores[0]);

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

    return 0;
}

How It Works

  1. Measure length once. sizeof(scores) / sizeof(scores[0]) → 3.
  2. Index from 0. Valid indexes are 0 … n-1, so use i < n.
  3. Read each element. scores[i] is the value at that index.
  4. Avoid pointer sizeof. If scores were a pointer parameter, this length trick would be wrong.

Edge Cases & Pitfalls

Check these before relying on for in real programs.

off-by-one

< vs <=

For indexes 0 … n-1, use i < n. i <= n reads one past the end.

update

Missing or wrong update

Forget i++ (or change the wrong variable) and the condition never fails → infinite loop.

sizeof

sizeof on a pointer

Inside a function that receives int *a, sizeof(a) is the pointer size. Pass length explicitly.

assign

= in the condition

for (...; i = n; ...) assigns, it does not compare. Use == or a relational operator.

Performance Notes

ApproachCostBest for
Simple for over nO(n)Counted work, array scans
Nested forO(n·m) or worseGrids, pairs — watch size
for vs whileSame orderPick the clearer form

Header overhead is tiny. Cost lives in the body and in nesting depth. Prefer clear bounds over clever tricks unless a profiler says otherwise.

Key Takeaways

  • Role: counted / index loops with init, test, and update in one place.
  • Order: init → test → body → update → test again.
  • Bounds: use i < n for indexes 0 … n-1.
  • Choice: for for counters; while/do-while for other stop rules.

One line: for means “start here, keep going while this is true, then bump.”

Frequently Asked Questions

A for loop repeats a block while a condition is true. It packs initialization, condition, and update into one header: for (int i = 0; i < n; i++) { ... }. Use it for counted work or clear stop rules.
Initialization runs once before the loop. Condition is checked before each iteration. Update runs after each iteration. Any part may be empty, but the two semicolons in the header are required.
Prefer for when a counter and stop rule belong together—counting, walking an array by index, or a fixed number of passes. Prefer while when you wait on input or an external event with no natural header counter.
Yes in C99 and later: for (int i = 0; i < n; i++). The variable’s scope is the loop. Compile with -std=c99 or newer. In older C, declare i before the loop.
The condition never becomes false—often a missing update, a wrong comparison, or using = instead of ==. Check that the loop variable moves toward making the condition false.
size_t n = sizeof(arr) / sizeof(arr[0]); then for (size_t i = 0; i < n; i++) { use arr[i]; }. Do not use sizeof on a pointer parameter—that gives pointer size, not the array length.

Next: while Loop

Repeat while a condition stays true—without a for header.

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.

8 people found this page helpful