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?
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.
This is a teaching runtime for a subset of C, running in your browser on a 32-bit model machine. It reports mistakes a real compiler lets through — reading uninitialised memory, running off an array, signed overflow — and it is not the compiler your project uses.
Press Run to see what your program does, or Check when you think it is right. Everything runs here in your browser.