0

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!

3
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by Salem
0

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.