typestar

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

  1. A for loop accumulates a running total.
  2. A while loop peels digits with /= 10.
  3. Both share the same total and digits state.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 7 in Operators & flow, step 10 of 35 in Language basics.

← Previous Next →