12. Program that calculates and prints the average of several integers. Assume that the last value read is sentinel 9999.

Chapter 6: 

Looping Structures

Programming Exercise

Problem # 12:

Write a program that calculates and prints the average of several integers. Assume that the last value read is sentinel 9999. A typical input sequence might be 10 8 6 7 2 9999 indicating that average of all values preceding 9999 is required.

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int n=0, num;
    float count=0,  avg;
    long int sum=0;
    while(num!=9999)
    {
        cout<<endl<<"Enter an integer (9999 to exit): ";
        cin>>num;
        if(num==9999)
        break;
        else
        {
            sum=sum+num;
            count++;
        n++;
        }
    }
    avg=sum/count;
    cout<<endl<<"The average is: "<<avg<<endl;  
    return 0;
}

Let me know in the comment section if you have any question.

Previous Post:
11. Program that inputs the number of students in the class. It then inputs the marks of these students and displays the highest and second highest marks.

Comments