954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Errors in counting number of elements of the array greater and lesser than average

Q.Write a program to input data in an array.Compute the sum and average.Then count the number of values greater than the average and lesser than the average.Print the average,sum and the two counts.

Solution I tried

#include<stdio.h>
int main(void)
{
int X[10],i,lesser=0,greater=0,sum=0;
float avg=0;
for(i=0;i<10;i++)
 {
 printf("Enter number\n");
 scanf("%d",&X[i]);
 }
for(i=0;i<10;i++)
 {
 sum=sum+X[i];
 avg=sum/10.0;
 if((float)X[i]>avg)
  {
  greater++;
  }
 else if((float)X[i]<avg)
  {
  lesser++;
                }
 }
printf("Average of numbers is %f\n",avg);
printf("sum of numbers is %d\n",sum);
printf("No of elements greater than avg are %d and lesser are %d",greater,lesser);
return(0);
}


Everything works fine but the counts computed are both wrong.Please help!

IwalkAlone
Light Poster
31 posts since Feb 2007
Reputation Points: 17
Solved Threads: 0
 

for(i=0;i<10;i++)
{
sum=sum+X[i];
}
calculate sum first then Average...
out of the for loop
avg=sum/10.0;

msvinaykumar
Light Poster
48 posts since May 2006
Reputation Points: 10
Solved Threads: 6
 

Your average is going to change each time around the loop.

Maybe one loop to calculate the sum, then calculate the average for the whole array (once), then another loop for the lesser, greater counts.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You