While Loops

This program loops to find the smallest, largest and the average.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Find total, count, print average 
#include <iostream>
using namespace std;
int main()
{ int count=0, total=0, num, small, large;
  cout<<"Enter number: ";
  cin>>num;  // read first number 
  small=large=num; //first num is smallest & largest so far.
  while (num>=0)
  { total+=num;
    count++;
    if (num < small) small = num; // store new smallest
    if (num > large) large = num; // store new largest 
    cout<<"Enter number (-1 to end): ";
    cin>>num; // read next number 
  } // while 
  cout<<"Total = "<<total;
  cout<<" Count = "<<count<<"\n";
  if (count > 0)  // avoid dividing by zero! 
  {  cout<<"Average = "<<1.0*total/count<<"\n";
     cout<<"The numbers range from "<<small<<" to "<<large<<"\n";
  } //print statistics if any numbers
  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.
  • Is the value that ends the loop included in the statistics?
  • What happens if the lowest or highest value appears twice?

NEXT: The do loop