Friday, 28 September 2018

Printing the sum and average of n numbers using an array in C++

Average of numbers

Average of numbers is the arithmetic mean of numbers. It is calculated when the sum of numbers is divided by the count of numbers being averaged.


Average of numbers
CALCULATION OF AVERAGE









Write a program in C++ to print the sum and average of n numbers using an array.


In this program, we input n numbers from the user with the help of array. We add each of the values to a variable and obtain the sum of n numbers. Then we divide the sum by n to obtain the average. The average must be assigned to float data type as it may have a decimal value.


Program

#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],n,i;
float sum=0,avg;
clrscr();
cout<<"How many numbers do you want to input=";
cin>>n;
cout<<endl;
if (n>50)
{
cout<<"Invalid input";
goto x;
}
for(i=1;i<=n;i++)
{
cout<<"Enter the number in a["<<i<<"]= ";
cin>>a[i];
sum=a[i]+sum;
}
avg=(sum/n);
cout<<endl<<"Sum= "<<sum;
cout<<endl<<"Average= "<<avg;
x:getch();
}



Output


Sum and average calculation using an array
SUM AND AVERAGE CALCULATION












Explanation


In the above program, we have declared an array a. The program will display an invalid input message if the input is greater than 50. It is because the array size is declared 50 and can't store more 50 values. The inputs are stored as subscripts or elements of an array. Then all these values are added to the sum variable. Then the average is calculated and displayed on the screen.




No comments:

Post a Comment