Hi Everyone,
I currently trying to calculate the average for an array. So far, I have input the monthly incomes for a store. I put the 12 months into an array and now I need to find the average monthly income. For example, if the monthly income for Jan-Dec was 10,000, then the average of the 12 months should be 10,000. However, I cannot figure out the code to output the average. Can you all help me? Thank you.
this is a simple program that programmed in C programming language and it is a console application
the code is programed and compiled in Code:Blocks program and it works
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
float sum=0;
float average;
float input[12];
char months[12][12]={"January","February","March","April","May","june","July","August","September","October","November","December"};
for( i=0;i<12;i++)
{
printf("Enter the income for %s",months);
printf(" : ");
scanf("%f",&input);
sum=sum+input;
}
average=sum/12;
printf("\n\nAverage is : %f",average) ;
Hi Everyone,
I currently trying to calculate the average for an array. So far, I have input the monthly incomes for a store. I put the 12 months into an array and now I need to find the average monthly income. For example, if the monthly income for Jan-Dec was 10,000, then the average of the 12 months should be 10,000. However, I cannot figure out the code to output the average. Can you all help me? Thank you.
Hassan's example should give you a good start. Think about how you'd calculate an average manually. You'd add all of the monthly incomes together to get a total, then divide to total (sum) by the number of elements (months). So that would be a for loop (0 to 11, which is 12 elements, since C starts all indices at zero). Start with sum = 0, then add January, then add Feb, etc. At the end, divide sum by 12 and viola, you have the average.
One other thing to be aware of is to make sure the sum variable is declared as a large enough data type to hold the final total (10,000 * 12 = 120,000, or possibly more). A float will handle it seamlessly, but if you declare sum as a short int, then you would run into problems with overflow.