OSC.005: C Loops — for, while, do-while, break, and continue

Photo-and-anime blend illustration of a fictional multiracial woman software engineer inspecting an embedded systems board and testing repeated LED control at her workstation

A loop is a C-language control structure that repeats a statement or compound block while a condition allows execution. The standard C constructs are for, while and do-while. Each can express repetition, but they differ in initialization placement, test timing, update behavior and what happens when a loop body must be interrupted.

This main-rotation lesson follows OSC.004: C Control Flow and complements the earlier lessons on the operators and expressions used in loop conditions and variable types used for loop counters. The goal is not simply to memorize syntax but to predict exactly when each block runs and how it terminates.

Learning objectives

  • Define iteration, initialization, condition, update expression and termination.
  • Distinguish pre-test for and while loops from the post-test do-while construct.
  • Trace the effect of break and continue on loop control, including nested loops.
  • Write and compile small, conforming C examples using GCC or Clang, with C99-or-newer syntax.
  • Identify off-by-one errors, counter-update mistakes and arithmetic-overflow hazards.
  • Use a bounded loop to process example equipment telemetry without treating a demonstration as a safety controller.

Definitions and the execution model

Iteration is one execution of the loop body. A condition is an expression evaluated for truth; in C, a scalar expression comparing equal to zero is false and a nonzero value is true. Initialization establishes the initial state. An update expression changes the state between iterations. A loop terminates when its condition becomes false or control explicitly leaves it, such as through break or return.

A useful diagnostic question is: “What changes between the current iteration and the next test?” If nothing relevant changes, a loop may continue indefinitely. The C language also permits intentionally unbounded forms such as for (;;), but production programs should have an explicit, reviewable exit path when waiting, polling or retrying.

ConstructWhen the condition is testedMinimum body executionsTypical use
forBefore each iteration, after one-time initialization0Counted or index-based repetition
whileBefore each iteration0Repeat while a state or input condition remains valid
do-whileAfter each body execution1Perform an action before deciding whether to repeat
The C-language distinction concerns the initial execution path; early return and similar control transfers can still end an enclosing function.

The for loop: initialization, test, body, update

The for statement groups three expressions or clauses: for (initialization; condition; update). Initialization runs once, the condition is checked before each body execution, and the update expression runs after the body. A continue within a for loop proceeds to the update expression before the next condition test. The C reference for for specifies this sequence.

for (int i = 0; i < 5; ++i) {
    printf("%d\n", i);
}
/* Prints 0, 1, 2, 3, 4 — NOT 5. */

The loop executes exactly five times because it starts at zero and stops once i < 5 is false. The declaration int i = 0 inside the initialization clause requires C99 or later; in that form, the name i has the loop’s scope rather than leaking into subsequent statements. This is an example of an exclusive upper bound. To produce 1 through 5 inclusive, start at one and compare i <= 5.

Video: Caleb Curry — C Programming All-in-One Tutorial Series (2019). For loops begin at 6:58:22; the video also covers while, do-while, break and continue.

For a known collection length, use a counter and a bounds condition rather than a sentinel that might never appear. Large indexes may be represented with size_t, which is designed for object sizes, but even that type is not immune to wraparound if incremented beyond its maximum. Prefer conditions that respect the actual array length and avoid unbounded arithmetic.

Video study: for loops and while loops

The independent freeCodeCamp C tutorial includes a section about while loops at approximately 2:29:43 and for loops at 2:50:11. It demonstrates the fundamental distinction between repetition while a condition holds and a loop with a visible counter. The course is for C, not C++ or C#.

Video: freeCodeCamp.org — “C Programming Tutorial for Beginners” (Mike Dane, 2018). Loop chapters begin at 2:29:43 (while) and 2:50:11 (for). A long-form English tutorial; captions and exact chapter times are supplied for targeted study.

The while loop: test before work

A while loop evaluates its condition before the first iteration and before every subsequent iteration. If the condition is initially false, the body is skipped entirely. The change that can end the loop is usually written inside the body, unlike the explicit update clause of a common for loop.

int remaining = 3;
while (remaining > 0) {
    printf("%d\n", remaining);
    --remaining;
}
/* Prints 3, 2, 1. */

In this example the decrement is essential. Omitting --remaining causes the controlling expression to stay true. A while loop is often appropriate when the number of iterations is not known in advance, such as reading valid input until it ends: while (scanf("%d", &value) == 1). That condition stops if the next conversion fails or input reaches end-of-file; it does not magically fix malformed input. The C while reference documents the pre-test behavior.

The do-while loop: run, then test

do { statement; } while (condition); executes its body before the condition is tested. It therefore performs one iteration even when the condition evaluates false at the first test. Notice the required semicolon after while (condition). This form suits an interaction that must happen once before a decision about repetition, such as displaying a menu or requesting an initial sample.

int attempts = 0;
do {
    ++attempts;
    printf("Attempt %d\n", attempts);
} while (attempts < 2);
/* Prints Attempt 1, then Attempt 2. */

Video: ProgrammingKnowledge — C Loops: for, while and do-while (2021). Distinct visual demonstration of pre-test and post-test loops.

Choose do-while only when executing the body once is legitimate and safe. It is not a shortcut for checking whether an array contains data; a do-while body that indexes an empty array could access invalid memory before the condition can prevent it. See Microsoft’s C-specific do-while documentation.

break and continue: leaving versus skipping

break immediately terminates the nearest enclosing for, while, do-while or switch; execution continues after that construct. continue does not exit the loop: it skips the rest of the current loop body and proceeds to the next iteration. In a for loop, it evaluates the update expression; in a while or do-while loop, it proceeds toward the controlling condition. Neither automatically exits multiple enclosing loops. See the C reference for break and continue.

for (int i = 0; i < 8; ++i) {
    if (i == 3) {
        continue;  /* Skip just 3; the ++i update still runs. */
    }
    if (i == 6) {
        break;     /* Stop before printing 6. */
    }
    printf("%d\n", i);
}
/* Prints 0, 1, 2, 4, 5. */

Beware the common bug while (i < limit) { if (skip) continue; ++i; }: when skip stays true, the increment never happens and the loop can become infinite. In a while loop, update any required state before continue, or restructure the loop so the update cannot be bypassed.

Video study: do-while, nested loops and control transfers

Bro Code’s C course contains distinct chapters on for loops at approximately 1:51:00, while at 1:54:22, do-while at 1:58:12, nested loops at 2:01:35 and break versus continue at 2:06:53. The demonstrations are useful for tracing the printed output, but their examples should be compiled with the target platform’s supported C language version.

Video: Bro Code — “C Programming Full Course for Free” (2021). Distinct English demonstration with for, while, do-while, nesting, break and continue at the chapter times listed above.

Compile and run a complete example

The following standalone example combines the basic constructions without accessing external hardware, allocating memory dynamically or requiring network access. It should compile with a conforming C11 compiler. Start with the OSC.001 C compiler and toolchain lesson if you need help installing GCC or Clang.

#include <stdio.h>

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

    int remaining = 3;
    while (remaining > 0) {
        printf("Countdown %d\n", remaining);
        --remaining;
    }

    int attempts = 0;
    do {
        ++attempts;
        printf("Attempt %d\n", attempts);
    } while (attempts < 2);

    for (int i = 0; i < 8; ++i) {
        if (i == 3) {
            continue;
        }
        if (i == 6) {
            break;
        }
        printf("Value %d\n", i);
    }

    return 0;
}

Expected standard output, with the values printed in order:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Countdown 3
Countdown 2
Countdown 1
Attempt 1
Attempt 2
Value 0
Value 1
Value 2
Value 4
Value 5

Save as loops.c, then compile with gcc -std=c11 -Wall -Wextra -Wpedantic -O0 -g loops.c -o loops and run ./loops on a Unix-like environment (or loops.exe from a suitable Windows shell). Compiler flags request C11 syntax and common warnings; they do not prove a program is free of all bugs. The logic is portable, but compiler invocation and terminal commands vary.

Applied example: scan equipment readings safely

A technician might receive a fixed-length list of nonnegative sensor readings, with -1 indicating missing data. The following C program ignores missing values using continue and stops at the first hypothetical alert threshold using break. It illustrates bounded array iteration only: it is not a real thermal safety controller, and 60 is a made-up teaching threshold, not an acceptable temperature for any ASIC or device.

#include <stdio.h>
#include <stddef.h>

int main(void)
{
    const int sensor_readings[] = {42, 47, -1, 64, 55};
    const size_t count = sizeof sensor_readings / sizeof sensor_readings[0];

    for (size_t i = 0; i < count; ++i) {
        int value = sensor_readings[i];

        if (value < 0) {
            continue;  /* Ignore missing-data marker. */
        }
        if (value >= 60) {
            printf("Alert at sample %zu: %d\n", i, value);
            break;     /* Stop reading after an alert. */
        }

        printf("Sample %zu: %d\n", i, value);
    }
    return 0;
}

The output is Sample 0: 42, Sample 1: 47 and Alert at sample 3: 64. Sample 2 is skipped, and sample 4 is never examined because the loop exits at sample 3. The sizeof expression computes the element count only because sensor_readings is an actual array in this scope; the same expression would not yield the array length after it decays to a pointer in a function parameter.

For physical equipment, sampling and trip logic also require independent fault handling, validated sensor specifications, fail-safe design and testing beyond this introductory example. Our hashboard thermal protection lesson demonstrates why missing readings and genuine overheating must be handled separately.

Nested loops, complexity and termination

A nested loop runs one loop body that itself contains another loop. For example, a five-by-four grid can be traversed with an outer row loop and an inner column loop; the inner body executes 20 times if each outer row makes four complete inner iterations. With input-dependent loop bounds, the number of iterations grows as the product of those bounds. Nested loops can be correct but unnecessarily expensive when used over large datasets. A break inside the inner loop only exits that inner loop; the outer loop continues unless additional state or control logic ends it.

for (int row = 0; row < 2; ++row) {
    for (int col = 0; col < 3; ++col) {
        printf("(%d,%d) ", row, col);
    }
    putchar('\n');
}
/* (0,0) (0,1) (0,2)
   (1,0) (1,1) (1,2) */

When diagnosing an apparent hang, inspect the condition, every relevant state update, early-continue paths and whether an external event is required for progress. A counter approaching its integer limits can also cause unwanted behavior: signed integer overflow is undefined in C, while unsigned arithmetic wraps modulo its range. Choose types and bounds deliberately and avoid increments that must overflow to reach a stopping condition.

Common mistakes and corrective patterns

  • Off-by-one boundary: i <= count iterates one more time than i < count. When indexing an array with count elements, the valid indexes are zero through count - 1.
  • Missing state update: a condition relying on an unchanged counter may remain true indefinitely.
  • Misplaced semicolon: while (condition); has an empty body. A following block is not the body of that loop.
  • Wrong equality expression: using assignment instead of comparison can change the loop’s state; revisit the earlier operators lesson.
  • Skipping updates with continue: update required while or do-while state before bypassing the remaining body.
  • Assuming break exits everything: it leaves only the nearest enclosing loop or switch.
  • Testing after use: do-while guarantees a body execution, which is wrong if the body must first verify input or array bounds.
  • Confusing demonstration and production: a loop that prints an alarm is not a validated industrial interlock or safety system.

Glossary and knowledge check

  • Body: the statement or block repeated by a loop.
  • Pre-test: the condition is evaluated before the body, as in for or while.
  • Post-test: the condition is evaluated after the body, as in do-while.
  • Sentinel: a special data value signaling a condition such as end-of-data or missing input; it must not collide with valid values.
  • Termination condition: the expression or control transfer that stops repetition.
  • Off-by-one error: a mistake producing one extra or missing iteration, often from choosing <= instead of <.

Check yourself: Why might while (0) run zero times while do { ... } while (0); runs once? If continue occurs in a for loop, is its update expression skipped? Why does the sample telemetry program ignore the third element? Which loop construct would you choose for a fixed 10-element array and why? What makes a runaway signed counter hazardous?

Answer guide: while is pre-test, but do-while is post-test; a for update still executes after continue; the telemetry’s third element is a missing-data sentinel; a bounded for loop is suitable for a known array length; signed overflow is undefined and should not serve as an exit mechanism.

References and further learning

Primary language references: C for statement; C while statement; C do-while statement; C break; C continue; and Microsoft’s C statement reference. Revisit conditional control flow, data types and compilation workflow before proceeding to the next distinct C curriculum topic.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support our work and help further secure the integrity of our research initiatives, please scan the QR code below to donate 5,000 sats.

Original BitcoinVersus.Tech QR code for a 5,000-satoshi Bitcoin donation

To scan from a phone, open this page on a laptop or larger screen and scan the QR with a compatible Bitcoin wallet. Verify the address before sending: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb.

BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

3 responses to “OSC.005: C Loops — for, while, do-while, break, and continue”

  1. […] This is an example of the same general principle discussed in our hashboard sensor diagnostics and C iteration lessons, although each language has its own memory […]

    Like

  2. […] data validation, and systems monitoring. For related loop syntax in another language, compare OSC.005: C Loops and OSRust.005: Rust Control […]

    Like

  3. […] Flow tutorial, and the Java switch reference to verify language behavior. Compare OSGo.004 and OSC.005 to see how related loop ideas differ across languages. The next Java track lesson can introduce […]

    Like

Leave a Reply