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.
CALCULATION OF AVERAGE |
Write a program in C++ to print the sum and average of n numbers without using an array.
In this program, we input the value of n and declare a for loop which iterates n number of time. We input the first numbers with the help of a variable and add it to a summation variable. Then we input the second number in the same variable that was used for the input of the first number and add it to the summation variable. In this way, all the numbers are added to the summation variable. The average is obtained by dividing the summation variable by n. The average must be assigned to float data type as it may have a decimal value.
The input value overwrites the previous value every time so it will not be stored in the program. If you want to store the input values then you must use an array for the input of numbers.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int m,n,i;
float sum=0,avg;
clrscr();
cout<<"How many numbers do you want to input=";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
{
cout<<"Enter the number m"<<i<<"= ";
cin>>m;
sum=m+sum;
}
avg=(sum/n);
cout<<endl<<"Sum= "<<sum;
cout<<endl<<"Average= "<<avg;
getch();
}
Output
SUM AND AVERAGE OF NUMBERS |
Explanation
In this program, we used a variable m to store input number. The user wanted to input 5 (i.e. n=5) numbers so the for loop executed as follows:
i(<=5) m sum=sum+m
i(<=5) m sum=sum+m
1 2 sum=0+2=2
2 5 sum=2+5=7
3 8 sum=7+8=15
4 9 sum=15+9=24
5 7 sum=24+7=31.
avg=(sum/n)=31/5=6.2
In the way, the value of sum and average was calculated and displayed on the screen.
2 5 sum=2+5=7
3 8 sum=7+8=15
4 9 sum=15+9=24
5 7 sum=24+7=31.
avg=(sum/n)=31/5=6.2
In the way, the value of sum and average was calculated and displayed on the screen.
No comments:
Post a Comment