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
- The Collatz
whileloop keeps halving or triplingnuntil it reaches 1. - The ternary picks
n / 2for even values and3 * n + 1for odd ones. do { ... } while (n > 0)divides at least once, so 0 still counts as one digit.
Keywords and builtins used here
collatz_stepscount_digitsdointreturnwhile
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.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.