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!

Recommended Answers

All 2 Replies

for(i=0;i<10;i++)
{
sum=sum+X;
}
calculate sum first then Average...
out of the for loop
avg=sum/10.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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.