Unit 1 · Lesson 618 minAcademic review pending

Doing it a hundred times without writing it a hundred times

Every counting loop has the same three moving parts. Once you can name them, while and for are the same idea written two ways.

Choose explanation

After this lesson

You should be able to

  • Identify the initialisation, test, and update in any counting loop.
  • Accumulate a sum or product correctly, including the starting value.
  • Convert a while loop to an equivalent for loop.
01

Three parts, always

A counting loop initialises a counter, tests it before each pass, and updates it at the end of each pass. Miss the initialisation and you start from garbage. Miss the update and the test never changes, so the loop runs forever.

while scatters the three parts across the program; for gathers them onto one line. That is the only real difference. Use for when you know the count in advance, while when the stopping condition depends on something you discover as you go.

The same loop, written twice
int i = 1;              /* initialise */
while (i <= 5) {        /* test       */
    printf("%d ", i);
    i = i + 1;          /* update     */
}

for (int i = 1; i <= 5; i++)   /* all three, one line */
    printf("%d ", i);
02

Accumulating a sum or a product

To total a series of values you need a variable that survives across passes. Set it to 0 before the loop and add into it each time. The starting value is part of the logic: a sum starts at 0 because adding zero changes nothing.

A product must start at 1, not 0. Start a product at zero and every answer is zero, because zero times anything is zero. The rule is to start with the value that does not disturb the operation.

Two accumulators, two starting values
int sum = 0, product = 1;

for (int i = 1; i <= 5; i++) {
    sum = sum + i;          /* 15  */
    product = product * i;  /* 120 */
}
03

Off-by-one is a design question

i <= n runs n times when i starts at 1. i < n runs n times when i starts at 0. Both are correct; mixing them is what produces a loop that runs one time too many or too few. Decide your convention and hold it.

Check a loop by hand with the smallest input, not a big one. Trace n = 1. If a loop is wrong, it is usually wrong at the very first or very last pass, and both are visible in a one-line trace.

Try it yourself

Read a positive integer n and print the sum of the first n natural numbers and their factorial, using a single loop.

Need a hint?

Two accumulators with two different starting values, updated in the same pass.

Check the worked solution

sum starts at 0 and product at 1 — the identity value for each operation. For n = 5 the output is 15 and 120. Note that factorial overflows an int quickly: 13! already exceeds the range, and C reports nothing when it does. That silent overflow is the reason long long appears here.

#include <stdio.h>

int main(void)
{
    int       n, sum = 0;
    long long product = 1;

    printf("Enter n: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        sum = sum + i;
        product = product * i;
    }

    printf("Sum = %d\n", sum);
    printf("Factorial = %lld\n", product);

    return 0;
}

Quick check

Why must a product accumulator start at 1 rather than 0?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Repetition in Programs · Counting Loops and the while Statement · Computing a Sum or Product in a Loop · for Statement

Maps to course outcomes CO1, CO2, CO3.