← Exercises|

Loops that count and accumulate

Write7 of 14 · about 6 min

Loops that count and accumulate

A for loop puts the three parts of a counted loop in one place: where it starts, when it keeps going, and what changes each time. A while loop is the same machinery with those parts scattered, which is why a counted loop reads better as a for.

Almost every loop you write in C either counts, accumulates, or searches. An accumulator is a variable declared before the loop, updated inside it, and used after it.

Declare the accumulator with a starting value. An uninitialised variable in C holds whatever was left in that memory — this runtime stops and tells you when you read one, which a real machine will not.

Example

int total = 0;
for (int i = 1; i <= 5; i++) {
    total += i;
}
printf("%d\n", total);   /* 15 */

Your task

Write int sum_to(int n) returning 1 + 2 + ... + n (and 0 when n is less than 1), and int count_digits(int n) returning how many decimal digits n has (treat 0 as having 1 digit; n is never negative).

Stuck?

Explain it

Why does count_digits(0) need its own case?

Not graded — this is for you.

Where this goes

Project 4 walks through every loop form and the patterns built from them. sum_to and count_digits are the two shapes you will reuse most.