Loops for Sums and Products

  1. Loops can be used to sum up a number of integers. If the integers are entered from the keyboard and stored in an integer variable next, and if the number of integers to be added is given by the variable this_many, one can add up these integers for example using a for-loop as follows:

    int sum(0),       // sum must be initialized to zero
          thisMany(21);       // total number of integers to be summed
    for (int count = 0; count < thisMany; count++)
    {
        cin >> next;
        sum += next;
    }

    Notice that count goes from 0 to (thisMany-1) and so exactly thisMany integers are summed. Alternately, the loop can be rewritten so that count goes from 1 to thisMany:

    for (int count = 1; count <= thisMany; count++)
    {
        cin >> next;
        sum += next;
    }

  2. Loops can be used to multiply a number of integers (or floats) together:

    int product(1);       // product must be initialized to one
          thisMany(21);       // total number of integers to be summed
    for (int count = 0; count < thisMany; count++)
    {
        cin >> next;
        product *= next;
    }