What is While Loop in C Explained- Embedded C Programming Course Online

🚀 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 6

While Loop in C Explained

Learn the while loop in C with syntax, flow diagrams, countdown, digit and polling programs. Part of our free C programming course for embedded systems.

A firmware main loop never stops, a UART driver waits until a flag is ready, and a bootloader retries until a flash write finishes. All three rely on repetition, and the simplest repetition tool in C is the while loop in C. This lecture is part of our free C programming course, a free C tutorial for C programming for embedded systems. You will learn the syntax, trace the execution step by step, and see the classic bugs in real compiled programs.

What You Will Learn

  • Why programs need loops and the three loop statements in C
  • The syntax of the while loop in C
  • How the entry-controlled test works pass by pass
  • How to write countdown, digit-sum and polling loops
  • Why a missing brace or stray semicolon breaks a loop
  • How firmware uses while (1) and why polling needs timeouts

Prerequisites

  • Lecture 5 on the else if ladder
  • Relational operators and increment/decrement from Chapter 4
  • gcc installed on Linux

Why Do We Need Loops in C?

Suppose a status LED must blink ten times. You could write ten copies of the same statement, but that wastes memory, invites typing errors and falls apart the moment the count changes to ten thousand. A loop lets you write the statement once and repeat it while a condition holds. C offers three loop statements: while, do while and for. This lecture covers the while loop in C, the simplest and most general of the three.

The three loop statements in C

while

Test firstMay run zero timesBest when the count is unknown

do while

Run firstAlways runs at least onceTest happens at the end

for

Setup, test and update in one lineBest when the count is knownCovered in a later lecture

While Loop Syntax in C

while (condition)
    statement;

For more than one statement, wrap them in braces to form a compound statement:

while (condition) {
    statement1;
    statement2;
}

The condition is an expression. C treats zero as false and any non-zero value as true. The loop body runs again and again for as long as the condition is true, and the program continues with the statement after the loop when it becomes false.

How the While Loop Executes

Execution cycle of a while loop

Step 1: evaluate the condition

Runs before every pass, including the first
▼

Condition TRUE

Run the loop bodyReturn to step 1

Condition FALSE

Skip the bodyContinue with the next statement

Entry-controlled loop

A while loop tests before each pass, so if the condition is false on the very first test, the body never runs at all. This is called an entry-controlled loop.

Program 1: Countdown With a While Loop

Every while loop needs three ingredients: something that sets up the condition, the condition itself, and something inside the body that moves the condition toward false. In the countdown, count is initialized before the loop, tested in the condition, and decremented in the body.

#include <stdio.h>

int main(void)
{
    int count = 5;

    while (count > 0) {
        printf("T-minus %d\n", count);
        count--;
    }
    printf("Lift off\n");
    return 0;
}
gcc -Wall -Wextra -std=c11 -o while1 while1.c
./while1
T-minus 5
T-minus 4
T-minus 3
T-minus 2
T-minus 1
Lift off
Passcount before testcount > 0 ?Action
15trueprint T-minus 5, count becomes 4
24trueprint T-minus 4, count becomes 3
33trueprint T-minus 3, count becomes 2
42trueprint T-minus 2, count becomes 1
51trueprint T-minus 1, count becomes 0
60falseloop ends, print Lift off

Program 2: Counting and Adding Digits

A while loop is the natural tool when you do not know in advance how many repetitions you need. Extracting the digits of a number is such a case: a five-digit number takes five passes and a ten-digit number takes ten. The remainder by 10 gives the last digit, and integer division by 10 drops it.

#include <stdio.h>

int main(void)
{
    unsigned int value = 40729;
    unsigned int copy = value;
    int digits = 0;
    unsigned int sum = 0;

    while (copy != 0) {
        sum += copy % 10;
        copy /= 10;
        digits++;
    }
    printf("Value %u has %d digits and digit sum %u\n", value, digits, sum);
    return 0;
}
gcc -Wall -Wextra -std=c11 -o while_digits while_digits.c
./while_digits
Value 40729 has 5 digits and digit sum 22
How 40729 is peeled apart

Pass 1

last digit 9remaining 4072

Pass 2

last digit 2remaining 407

Pass 3

last digit 7remaining 40

Pass 4

last digit 0remaining 4

Pass 5

last digit 4remaining 0, loop stops

Program 3: Polling a Peripheral Flag

The most common while loop in embedded C programming is the polling loop: keep checking a status flag until the hardware reports it is ready. The program below simulates a peripheral that becomes ready on the fourth read, so you can see the pattern without any hardware.

#include <stdio.h>

/* Pretend hardware: status flag becomes 1 on the 4th read */
static int read_status(void)
{
    static int calls = 0;
    calls++;
    return calls >= 4;
}

int main(void)
{
    int attempts = 0;

    while (read_status() == 0) {
        attempts++;
        printf("Peripheral busy, retry %d\n", attempts);
    }
    printf("Peripheral ready after %d retries\n", attempts);
    return 0;
}
gcc -Wall -Wextra -std=c11 -o while_poll while_poll.c
./while_poll
Peripheral busy, retry 1
Peripheral busy, retry 2
Peripheral busy, retry 3
Peripheral ready after 3 retries
Real hardware polling needs a timeout

If the flag never becomes ready because of a broken peripheral or a wrong clock setting, a bare polling loop hangs the whole system forever. Real drivers add a retry counter or a timer and report an error when it expires. Also remember that variables changed by hardware or interrupts must be declared volatile so the compiler does not optimize the test away.

Single Statement Body Versus Block

Without braces, only the first statement after the condition belongs to the loop. Indentation does not change that. Here is the trap:

#include <stdio.h>

int main(void)
{
    int n = 1;

    while (n <= 3)
        printf("Line %d\n", n);   /* only this is in the loop */
        n++;                       /* this is NOT */
    return 0;
}

This program prints Line 1 forever. The statement n++; is outside the loop even though it is indented as if it were inside, so n never changes and the condition stays true. gcc warns with -Wmisleading-indentation. Braces fix it, and so does moving the increment into the expression:

#include <stdio.h>

int main(void)
{
    int n = 1;

    while (n <= 3)
        printf("Line %d\n", n++);
    return 0;
}
Line 1
Line 2
Line 3

The Semicolon After While Bug

A stray semicolon right after the condition creates an empty loop body. The braces that follow then become an ordinary block that never repeats.

#include <stdio.h>

int main(void)
{
    int i = 0;

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

This program prints nothing and never ends, because while (i < 3); loops on an empty statement while i stays zero. The compiler flags it with the same misleading indentation warning. The rule: never put a semicolon directly after while (condition) unless you truly want an empty body, and in that case write the empty body as {} or a commented ; on its own line.

Infinite Loops: Bug or Feature?

A condition that is always true creates an infinite loop. In a desktop program that is usually a bug. In firmware it is the heart of the design, because a microcontroller must never return from main. The idiomatic form is while (1) { ... } for the main super-loop that reads inputs, updates outputs and services tasks forever.

KindExampleIntentional?
Super loop in firmwarewhile (1) { service_tasks(); }Yes
Forgot to update the variablewhile (i < 10) { work(); }No, bug
Semicolon after the conditionwhile (i < 3);No, bug
Condition that never changeswhile (flag) { } with a non-volatile flag set in an ISRNo, bug

Common Mistakes With the While Loop in C

Mistake 1: forgetting to update the loop variable

If nothing in the body moves the condition toward false, the loop never ends.

Mistake 2: off-by-one errors

Using <= where < was needed runs one extra pass. Trace the first and last pass by hand.

Mistake 3: assigning instead of comparing

while (x = 5) assigns 5 and is always true. Use ==.

Mistake 4: relying on indentation

Use braces for every loop body so a later edit cannot silently fall outside the loop.

Best Practices

  • Always use braces, even for a one-line body.
  • Initialize the loop variable immediately before the loop.
  • Make the progress step obvious and close to the end of the body.
  • Add a timeout or retry limit to every hardware polling loop.
  • Declare hardware-updated flags as volatile.
  • Compile with -Wall -Wextra to catch misleading indentation.

Performance and Security Considerations

A tight polling loop keeps the CPU awake and drains the battery. Where hardware allows it, prefer interrupts or a low-power wait instruction. From a safety point of view, an unbounded loop that waits on external input is a denial-of-service risk, which is another reason to bound every wait with a timeout.

Key Takeaways

  • A while loop repeats its body as long as the condition is true.
  • The condition is tested before every pass, so the body may run zero times.
  • A loop needs setup, a test and a progress step.
  • Without braces only one statement belongs to the loop.
  • A semicolon after the condition creates an empty body and usually an infinite loop.
  • while (1) is the standard super loop of firmware, and polling loops need a timeout.

Conclusion

You now understand why loops exist, how the while loop in C executes, and the traps that catch beginners: missing braces, stray semicolons and forgotten progress steps. This free C programming course continues with the do while loop and the for loop. If you are using this free C tutorial to learn C programming for embedded systems, try rewriting each example here with different values before moving on.

Frequently Asked Questions

What is a while loop in C?

It is a loop that repeats its body as long as a condition stays true, testing the condition before each pass.

Can a while loop run zero times?

Yes. If the condition is false on the first test, the body is skipped entirely.

How do I write an infinite loop in C?

Use while (1) { … }. Firmware uses this as the main super loop because the program must never return from main.

What does a semicolon after while do?

It makes the loop body an empty statement. The loop spins on the test and the following block runs once or never, depending on the condition.

What is the difference between while and do while?

While tests first and may run zero times. Do while runs the body first and tests at the end, so it runs at least once.

Why use volatile in a polling loop?

A flag changed by hardware or an interrupt can be cached in a register by the compiler. Volatile forces a real read on every test.

How do I stop a while loop early?

Use break to leave the loop or continue to skip to the next test. Both are covered in a later lecture.

Is there a free embedded C course that covers loops?

Yes. This free embedded C course and free C tutorial cover while, do while and for loops with tested examples and quizzes.

Continue Learning Embedded C Programming

Next up: the do while loop and the for loop. Keep going with this free embedded C course and free C tutorial.

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 →