What is For Loop in C- Free Embedded Systems and C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free C Programming Course · Chapter 5 · Lecture 10

For Loop in C

Learn how the for loop in C combines initialisation, condition and update, and how to trace it step by step. A hands-on lecture from our free C programming course for embedded systems.

The for loop in C is the loop you will write more than any other, because most real tasks repeat something a known number of times. Scanning ADC channels, filling a buffer and blinking an LED ten times are all counted jobs. This lecture is part of our free C programming course and free C tutorial, built for embedded C programming beginners.

Every program in this lecture was compiled with GCC and run, and the output shown is real. You will learn the exact order in which the three expressions execute, so you can predict any loop before you run it.

What You Will Learn

Syntax of the for loop in C Roles of the three expressions Execution order step by step For versus while equivalence Comma operator and flexible forms Infinite for loops in firmware Off by one and stray semicolon bugs Best practices and FAQ

Prerequisites

  • While and do while loops from the earlier lectures
  • Relational operators from Chapter 4
  • GCC installed on Linux

For Loop in C: Syntax and the Three Expressions

The for loop in C gathers everything a counted loop needs into one line: where to start, when to continue and how to move forward. Here is the general form:

for (expression1; expression2; expression3)
    statement;

for (expression1; expression2; expression3) {
    statement1;
    statement2;
}

The body can be one statement or a block in braces. The three expressions live inside the parentheses and are separated by two semicolons. Each has a fixed job:

ExpressionNameTypical contentHow often it runs
expression1Initialisationi = 0Once, when the loop starts
expression2Conditioni < 10Before every pass, including the first
expression3Updatei++After every pass of the body

The condition normally uses relational and logical operators from the previous chapter. The update changes a loop variable so the condition can eventually become false.

How a For Loop in C Executes

The order matters more than the syntax. Learn this sequence once and every for loop becomes easy to trace.

Execution order of a for loop
1. Run the initialisation once
▼
2. Is the condition true?
false▶Leave the loop
true▶3. Run the body▶4. Run the update▶Back to step 2

Two details trip up beginners. The update runs after the body, not before it. And the condition is tested before the very first pass, so a for loop can run zero times. The program below prints a message on every pass so you can watch the order:

#include <stdio.h>

int main(void)
{
    int n;

    for (n = 3; n > 0; n--) {
        printf("test passed, body runs with n=%d\n", n);
    }
    printf("exit with n=%d\n", n);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o trace trace.c
./trace
test passed, body runs with n=3
test passed, body runs with n=2
test passed, body runs with n=1
exit with n=0

The loop variable is 0 when the loop exits. That value is the first one that failed the test, not the last one that passed. This is why code that uses the counter after the loop must remember it is one step beyond the final pass.

Passn at testTest resultBody runsn after update
13trueyes2
22trueyes1
31trueyes0
exit0falsenounchanged

For Loop in C Compared with While

Every for loop can be rewritten as a while loop, and the reverse is also true. The conversion is mechanical: move the initialisation above the loop, keep the condition in the parentheses and put the update as the last statement of the body.

for (init; cond; update)
    body;

/* equals */

init;
while (cond) {
    body;
    update;
}
Same loop, two spellings
for▶init, test and update on one line▶body
while▶init above▶test on top▶body then update

So why have both? Because of readability. A for loop keeps the three counter-related decisions together, which makes it the first choice when you know the iteration count in advance. A while loop is better when the stopping point depends on something that appears during the run. The next program prints a counted sequence three ways so you can see they match:

#include <stdio.h>

int main(void)
{
    int i;

    printf("up:   ");
    for (i = 1; i <= 5; i++)
        printf("%d ", i);

    printf("\ndown: ");
    for (i = 20; i >= 5; i -= 5)
        printf("%d ", i);

    printf("\nafter loop i=%d\n", i);

    /* the same first loop as a while loop */
    printf("while version: ");
    i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    printf("\n");
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o forbasic forbasic.c
./forbasic
up:   1 2 3 4 5 
down: 20 15 10 5 
after loop i=0
while version: 1 2 3 4 5

The second loop counts down in steps of five and finishes with the variable at 0, one step past the last printed value. The while version reproduces the first loop exactly.

QuestionPrefer forPrefer while
Is the number of passes known?YesNo
Is there a simple counter?YesNot necessarily
Does a hardware event end the loop?RarelyOften
Where should the update live?In the headerIn the body

Flexible Forms of the For Loop in C

Every expression is optional, and the update or initialisation can hold more than one action when you separate them with the comma operator. These variations appear constantly in embedded code, so recognise them early.

#include <stdio.h>

int main(void)
{
    int lo, hi;
    int k = 0;

    /* two variables in one loop using the comma operator */
    for (lo = 0, hi = 9; lo < hi; lo++, hi--)
        printf("lo=%d hi=%d\n", lo, hi);

    /* initialisation moved out, update moved into the body */
    for (; k < 3; )
        printf("k=%d\n", k++);

    /* C99 loop-scoped counter */
    for (int j = 0; j < 2; j++)
        printf("j=%d\n", j);

    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o forforms forforms.c
./forforms
lo=0 hi=9
lo=1 hi=8
lo=2 hi=7
lo=3 hi=6
lo=4 hi=5
k=0
k=1
k=2
j=0
j=1
  • Two counters: the first loop walks inward from both ends, which is how you reverse a buffer in place.
  • Moved parts: the second loop leaves the first and third slots empty, but both semicolons must stay.
  • Loop-scoped counter: since C99, for (int j = 0; ...) limits the variable to the loop, which prevents accidental reuse. It needs a C99 or newer compiler mode.

An empty condition means true. The form for (;;) is therefore an infinite loop, and it is a common way to write the super loop of a firmware main function:

for (;;) {
    poll_buttons();
    update_display();
}

Why for (;;) and not while (1)?

Both compile to the same code. Some teams prefer for (;;) because static analysers never warn about a constant condition. Pick one style and keep it consistent across the project.

Common For Loop Mistakes

These bugs are small to type and expensive to find. The program below demonstrates two of them with real output.

#include <stdio.h>

int main(void)
{
    int i;
    int hits = 0;

    for (i = 0; i <= 5; i++)       /* <= runs one extra time */
        hits++;
    printf("<= 5 ran %d times\n", hits);

    hits = 0;
    for (i = 0; i < 5; i++);       /* stray semicolon */
        hits++;
    printf("with stray semicolon body ran %d time\n", hits);

    unsigned int u;
    printf("unsigned countdown: ");
    for (u = 3; u != (unsigned int)-1; u--)
        printf("%u ", u);
    printf("(stops only because of the explicit test)\n");
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o bugs bugs.c
./bugs
<= 5 ran 6 times
with stray semicolon body ran 1 time
unsigned countdown: 3 2 1 0 (stops only because of the explicit test)
Off by one. Using <= where < was meant ran the body six times instead of five. Arrays make this dangerous, because the last index is one less than the length.
Stray semicolon. A semicolon directly after the closing parenthesis is an empty loop body. The loop runs five times doing nothing and the indented statement runs once afterwards. GCC flagged it with -Wmisleading-indentation, which is a good reason to compile with -Wall -Wextra.
Unsigned countdown. A loop like for (u = 3; u >= 0; u--) with an unsigned variable never ends, because an unsigned value cannot go below zero. GCC reports that the comparison is always true when -Wextra is enabled. Count down with a test such as u != 0 and handle zero separately, or use a signed type.
Changing the counter inside the body. Modifying the loop variable in the body makes the loop hard to read and is a frequent source of skipped or repeated passes. Leave the counter to the header.

Best Practices for Writing a For Loop in C

Habits worth keeping

  • Use a half-open range: start at 0 and test with < against the length.
  • Keep the loop variable local to the loop with C99 syntax when your toolchain allows it.
  • Use a clear name such as idx or channel when the counter has meaning.
  • Do not rely on the counter value after the loop unless you document it.
  • Prefer unsigned types for array indexes, and never test an unsigned counter against less than zero.
  • Compile with -Wall -Wextra and treat warnings as bugs.

Performance: a for loop and an equivalent while loop produce nearly identical machine code, so choose by clarity. On small microcontrollers, a loop with a constant bound may be unrolled by the optimiser. Safety: a loop bound taken from received data must be checked against the buffer size before the loop starts, otherwise a malformed packet can drive the index past the end of the array.

Key Takeaways

  • The for loop in C has an initialisation, a condition and an update, separated by semicolons.
  • Initialisation runs once, the condition runs before every pass, the update runs after every pass.
  • A for loop can run zero times, and the counter ends one step beyond the last pass.
  • Any for loop can be rewritten as a while loop and the other way round.
  • Use for when the iteration count is known, while when it is not.
  • Off-by-one errors, stray semicolons and unsigned countdowns are the classic bugs.

Conclusion

The for loop in C looks simple, yet it is the loop you will write most often in firmware: filling buffers, scanning channels, repeating a hardware action a fixed number of times. Knowing the exact order of the three expressions removes nearly all the guesswork when you debug.

In the next lecture you will put the for loop to work on practical programs: counting up and down, repeated addition, series sums and a small embedded checksum.

Frequently Asked Questions

What is a for loop in C?

It is a counted loop with an initialisation, a condition and an update written in one statement, used when the number of iterations is known.

In what order do the three for loop expressions run?

Initialisation once, then condition before each pass, then body, then update, then back to the condition.

Can a for loop run zero times in C?

Yes. If the condition is false at the first test, the body never runs.

What does for(;;) mean in C?

An empty condition counts as true, so it is an infinite loop, often used for the main super loop in firmware.

What is the difference between for and while in C?

They are equivalent in power. For keeps setup, test and update together, while while is better when the end depends on events.

Why is the loop variable one past the end after the loop?

The loop exits when the condition fails, and the failing value is the one left in the variable.

Can I declare a variable inside the for loop header?

Yes, from C99 onward. The variable exists only inside the loop.

Is this part of a free embedded C course?

Yes. It belongs to our free embedded C course and free C programming course, and all examples were compiled and run.

Practice the For Loop Next

Continue with practical for loop programs in the next lecture of this free C tutorial for embedded C programming.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →