for and while loops in C
C's counting and condition-driven loops.
int sum_and_digits(int limit) {
int total = 0;
for (int i = 1; i <= limit; i++)
total += i;
int n = limit, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
return total + digits;
}
How it works
- A
forloop accumulates a running total. - A
whileloop peels digits with/= 10. - Both share the same
totalanddigitsstate.
Keywords and builtins used here
forintreturnsum_and_digitswhile
The run, in numbers
- Lines
- 12
- Characters to type
- 181
- Tokens
- 65
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 46 seconds.
Step 3 of 7 in Operators & flow, step 10 of 35 in Language basics.