11. Counter, Arithmetic Mean and Division by Zero

Accumulating the Product

Problem: Write a program that reads in one natural number n. The program should output the product of all natural numbers not greater than n.

The solution to this problem is similar to the summing up algorithm. The sum in the summing up algorithm is accumulating the summands, and the difference is that factors need to be accumulated in order to calculate the product. As the terms are accumulated by the operation of addition, so are the factors accumulated by the operation of multiplication.

Another crucial aspect of accumulating products is that the starting value should not be zero. If the product was to start with zero, it would never change, since the zero stays zero no matter what number it gets multiplied by. Instead, the product has to start with a value 1, which is a neutral element for multiplication:

    int product = 1;

Then the program just has to accumulate all the factors. To go through all the natural numbers not greater than n, a for loop can be used:

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

Of course, the second line can be written more succinctly.

This is the entire program:

#include <iostream>
using namespace std;

int main() 
{     
    cout << "Type in number n:" << endl;
    int n;
    cin >> n;
    
    int product = 1;
    for (int i=1; i<=n; i++)
        product *= i;
    
    cout << "The product of first n natural numbers is: " << product;
    cout << endl;
}

The output might be:

Type in number n:
5
The product of first n natural numbers is: 120

This program is likely to give you a wrong result whenever n is greater than 12. Why? The variables of type int cannot store very big numbers. This will be discussed in another chapter.