SovranCode
HomeCourses C C While Loop
This device
Course contentsC While Loop · 21 titles

C Fundamentals

C IntroductionC First ProgramC VariablesC Data TypesC OperatorsC Input and Output

Control Flow

C If ElseC For LoopC While Loop

Functions and Collections

C FunctionsC ArraysC Strings

Memory and User-Defined Types

C PointersC StructuresC EnumsC Dynamic Memory

Files, Tooling, and Projects

C File HandlingC PreprocessorC DebuggingC MakefilesC Project: Command-Line Inventory Manager
Learn C Programming21 complete lessons

C Fundamentals

C IntroductionC First ProgramC VariablesC Data TypesC OperatorsC Input and Output

Control Flow

C If ElseC For LoopC While Loop

Functions and Collections

C FunctionsC ArraysC Strings

Memory and User-Defined Types

C PointersC StructuresC EnumsC Dynamic Memory

Files, Tooling, and Projects

C File HandlingC PreprocessorC DebuggingC MakefilesC Project: Command-Line Inventory Manager
PREVIOUS LESSONC For Loop
NEXT LESSONC Functions
Control Flow 50 min

C While Loop

Repeat work while a condition remains true, change state each pass, and keep an obvious exit.

What you will leave with

You will be able to write a while loop with a named initial state, condition, and update; explain the zero-cycle case; use do/while only when the body must run once; and keep break and continue exceptional.

Use while when changing state defines the stop

A while loop continues until some state changes: tasks remaining, a retry count, or a validated input. Its condition appears at the top, so it may run zero times. That is often correct when there is no work to do. Prefer C For Loop when the repetition count is known before the first cycle.

C FUNDAMENTALS RUNNER

Make a while loop finish

remaining controls the loop and remaining-- changes that same value each cycle.

#include <stdio.h>

int main(void) {
  int remaining = 3;

  while (remaining > 0) {
    printf("%d task(s) remain.\n", remaining);
    remaining--;
  }
  puts("All tasks are complete.");
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Start with 5 tasks, then label even and odd remaining counts using an if branch.

Every loop needs a progress story

Identify the condition and the statement that can make it false. This browser runner stops after many cycles to protect the page; a real program needs a correct update of its own.

Trace a while loop before you write it

Start with remaining = 3. The condition remaining > 0 is true, so the body prints 3 and remaining-- stores 2. After printing 1, the update stores 0; 0 > 0 is false, so the completion message prints. At the start of every pass, remaining is the number of tasks not yet reported—that repeated fact is a loop invariant.

remaining = 0

Zero-cycle case

The body runs zero times. The statement after the loop still runs.

remaining = 1

One-cycle case

The body runs once, then the update reaches the stopping boundary.

remove remaining--

Failure case

The condition keeps reading the same positive value.

Use do-while only when one attempt must happen first

A do/while loop tests after its body, so the body runs at least once even if the condition is already false. That matches a prompt that must appear before the user can stop. If the work may legitimately happen zero times, use while.

C FUNDAMENTALS RUNNER

Run a first check before testing again

The body prints once before checks < 2 is evaluated.

#include <stdio.h>

int main(void) {
  int checks = 0;

  do {
    printf("Check %d\n", checks + 1);
    checks++;
  } while (checks < 2);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change the condition so the program prints exactly three checks.

break and continue target the nearest loop

break leaves immediately. continue returns to the while condition. If you continue before the update, you can create an infinite loop. Put the state change where every path that should continue still performs it—or use a for loop whose update always runs.

C FUNDAMENTALS RUNNER

Skip one cycle and stop after a found result

Increment happens before continue, so attempt still moves.

#include <stdio.h>

int main(void) {
  int attempt = 0;

  while (attempt < 5) {
    attempt++;
    if (attempt == 2) {
      puts("Skip attempt 2.");
      continue;
    }
    printf("Check attempt %d\n", attempt);
    if (attempt == 4) {
      puts("A valid result appeared.");
      break;
    }
  }
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change the skipped attempt to 3 and the successful attempt to 5.

Independent lab: a retry limit

Write a loop that continues while attempt < 3, prints the attempt number, and increments. Then add a path that breaks early on a successful dummy condition. Prove that removing the increment would not finish.

Lesson review

  • while tests first and may run zero times.
  • Name the initial state, the condition, and the update that can stop it.
  • do/while runs at least once.
  • continue must not skip the update that makes progress.

Related lessons

  • C If Else — The condition in a while loop is the same idea as if.
  • C For Loop — Prefer for when the repetition count is visible from the start.
KNOWLEDGE CHECK

Name the condition and the update

A while loop needs an initial state, a condition, and a change that can make the condition false.

01When is while usually the clearer loop?
02What is missing from while (attempt < 3) { puts("Try again"); }?
03How does do-while differ from while?
04What does break do inside a while loop?
05If remaining starts at 0, how many times does while (remaining > 0) run?
PREVIOUS LESSONC For Loop
NEXT LESSONC Functions
ON THIS PAGEC While Loopwhile syntaxTracingdo-whilebreak and continueIndependent labLesson reviewKnowledge checkRelated lessons
Course contents