211: Programming For IS 1 --- Lecture Oct. 20

Topics:

Review of Repetition Control Stuctures while, do/while & Menu-Driven Programs
Repetition Control Structure: for
Nested Loops
Using a Sentinel

Syntax: for statement

for(<data class> <counter> = <initial value>; counter test expression; increment/decrement counter)
{

} //END for

As usual when there is only one statement the curly brackets can be omitted.

To illustrate the use of the for statement, we revisit the problem of computing the numbers from 1 to n, which we solved using a while statement in the Oct. 13 lecture.

//For a given positive integer N, this program uses a for loop to
compute the sum of the numbers from 1 to N.

#include <iostream.h>  // used for cout and cin

int main()
{
   int Sum = 0;
   int N;

   cout << "Please enter a positive integer N: ";
   cin >> N;

   //COMPUTE SUM OF NUMBERS FROM 1 TO N
   for (int Counter = 1; Counter <= N)
        Sum += Counter;
     
   //DISPLAY RESULT
   cout << "The sum of the numbers from 1 to " << N << " is " << Sum
        << '.' << endl;
   return 0;
} //END 

Nested Loops and Using a Sentinel

Suppose we wish to compute the sum of the numbers from 1 to N for many different values of N. This is accomplished in the next program using nested loops. We have an outer while loop that is executed until the user enters a negative integer, and an inner for loop that computes the sum. The negative integer is called a sentinel value, because its purpose is simply to mark the end of the sequence of integer N's being input, and it is not actually a part of the input data, i.e., an N for which we are computing a sum.

#include <iostream.h>  // used for cout and cin

int main()
{
   int Sum = 0;
   int N;

   cout << "Please enter a positive number N, or negative number to terminate: ";
   cin >> N;
   //KEEP LOOPING UNTIL A NEGATIVE NUMBER IS INPUT
   while (N > 0)
   { 
        //COMPUTE SUM OF NUMBERS FROM 1 TO N
        for (int Counter = 1; Counter <= N)
             Sum += Counter;

        //DISPLAY RESULT
        cout << "The sum of the numbers from 1 to " << N << " is " << Sum
             << '.' << endl;
        cout << "Please enter a positive number N, or negative number to terminate: ";X
        cin >> N; //INPUT ANOTHER INTEGER N
        Sum = 0; //INITIALIZE Sum TO 0 FOR NEW PASS AND SUMMATION COMPUTATION
   }//END OUTER while loop 
   return 0;
} //END