While Loops

In this program there are no values that are outside the valid data. We must ask each time if there are more values.

Notice that we check if the answer is either 'Y' or 'y'. We do not use and because no character can be both 'y' AND 'Y'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Find total, count, print average while 'Y' loop
#include <iostream>
using namespace std;
int main()
{ int count=0, total=0, num;
  char answer='Y'; 
  cout<<"Are there any numbers (Y or N):";
  cin>>answer;
  while (answer=='Y' || answer=='y') //accept either Y or y
  { cout<<"Enter number: ";
    cin>>num; // read next number 
    total+=num;
    count++;
    cin.ignore(100,'\n'); //flush the \n from the buffer
    cout<<"Are there more numbers (Y or N):";
    cin>>answer;
  } // while 
  cout<<"Total = "<<total;
  cout<<" Count = "<<count<<"\n";
  if (count > 0)  // avoid dividing by zero! 
    cout<<"Average = "<<1.0*total/count<<"\n";
  return 0;
} // main
CODE

To Do:

  • Run the program in your compiler. Try different sets of numbers.
  • Enter data that will cause the value of count to be 0.
  • What values can end the loop?

NEXT: Display "pass" or "fail" for each grade