typestar

While & do-while in C++

while tests before every pass; do-while runs the body once before it ever asks.

int collatz_steps(int n) {
    int steps = 0;
    while (n > 1) {
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    return steps;
}

int count_digits(int n) {
    int digits = 0;
    do {                              // runs at least once, even for 0
        n /= 10;
        digits++;
    } while (n > 0);
    return digits;
}

How it works

  1. The Collatz while loop keeps halving or tripling n until it reaches 1.
  2. The ternary picks n / 2 for even values and 3 * n + 1 for odd ones.
  3. do { ... } while (n > 0) divides at least once, so 0 still counts as one digit.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
286
Tokens
85
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →