An Example of a while Loop



#include <iostream.h>
/**********************************************************************
 Program: while_loop1.C
 This program computes an average of all the numbers keyed in
 This program also has the same errors as do_while.C 
**********************************************************************/

int main()
{
     int num = 0, count = 0, total = 0;

     while (num != -99) { // test the condition
          cout << "Enter a whole number, and -99 to quit:";
          cin >> num; // accept input
          count++; // increment counter 
          total += num; //accumulate the sum 
     } 
     
     cout << "You keyed in " << count << " numbers \n";
     cout << "The total is " << total << endl;
     cout << "The average is " << float(total)/count << endl;
     return(0);
}




/**********************************************************************
 Program: while_loop2.C
 This program computes an average of all the numbers keyed in
 This is the debugged version of while_loop1.C
**********************************************************************/
#include <iostream.h>

int main()
{
     int  num, count = 0, total = 0;

     cout << "Enter a whole number, and -99 to quit:";
     cin >> num; // accept input
     while (num != -99) { // test the condition
          count++; // increment counter 
          total += num; //accumulate the sum 
          cout << "Enter a whole number, and -99 to quit:";
          cin >> num; // accept input
     } 
     
     cout << "You keyed in " << count << " numbers \n";
     cout << "The total is " << total << endl;
     cout << "The average is " << float(total)/count << endl;
     return(0);
}



Back to Previous Page

Document:
Local Date:
Last Modified On: