While Loops

How to Use a While Loop: An Example

Walk through a C++ while loop example that counts the digits of a number, pass by pass, with a trace table and a complete program you can compile.

On this page
  1. The example: counting digits
  2. How the loop runs
  3. Trying the edge cases
  4. What to check in your own while loops

A while loop runs its body once per pass, checking the condition before each pass. This example counts the digits in a whole number. The number of passes depends on the number itself, so a while loop fits the job well.

The example: counting digits

#include <iostream>

int main() {
    int n = 90817;
    int digits = 0;

    while (n > 0) {
        n /= 10;   // drop the last digit
        ++digits;  // count one digit
    }

    std::cout << "Number of digits: " << digits << '\n';
    return 0;
}

Output:

Number of digits: 5

How the loop runs

Each pass divides n by 10 and adds one to digits. The table shows the values on each pass:

Pass n at the start of the pass n after n /= 10 digits after the pass
1 90817 9081 1
2 9081 908 2
3 908 90 3
4 90 9 4
5 9 0 5

After pass 5, n is 0, so the condition n > 0 is false and the loop ends with digits equal to 5. Integer division drops the fraction, so 90817 / 10 is 9081, which removes the last digit each time. The /= is shorthand for n = n / 10, one of the c assignment operators.

Trying the edge cases

If n starts at 0, the condition is false from the start, the body never runs, and digits stays 0. That is a zero-pass case. It is also a quirk of this version, because the number 0 has one digit, so a complete program would add a special case for it.

Negative numbers also give 0 here, since n > 0 is false from the start. Handling them takes an extra step that is outside this example.

What to check in your own while loops

  • Confirm that the body changes at least one variable the condition depends on. Here that is n.
  • Trace the first two or three passes on paper, as the table does, before you run the code.
  • While debugging, print the variables inside the loop, then remove the prints.

For the syntax rules and common mistakes behind this pattern, see c while loop syntax.

The complete guide to while loops

C++ While Loop Syntax
Read the guide

Keep exploring

Guides from other topics

All topics →

Inheritance in C++

A practical guide to inheritance in C++: the syntax, access specifiers, constructor order, virtual functions and common mistakes, with short code examples.

Inheritance 7 min read

SOLID Principles in C++

Learn the five SOLID principles in C++ with short examples of single responsibility, open/closed, Liskov, interface segregation and dependency inversion.