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!

Dani AI

Generated

The counts are wrong because the program compares each element to a moving, incorrect average. In the posted code the running sum is updated inside the same loop that does the comparisons, and avg is recomputed each iteration using the fixed divisor 10. That produces a different baseline for each element (and usually a much smaller one early on), so many values will be classified incorrectly. Both and were right to suggest separating the work — compute the final average once, then do the comparisons.

Concrete example: if the first value is 10, after that single update the code computes avg = 10 / 10.0 = 1.0, so the first element is counted as greater even though the final average (after all 10 inputs) might be 5.0. Repeating this for every element skews the totals.

Correct approach (no code shown): read and store the inputs; run one pass to compute the total sum; compute the final avg = sum / n (use n rather than a hard-coded 10); then run a second pass through the stored values to increment greater, lesser (and optionally an equal counter). That guarantees comparisons are against the true average.

Additional tips: to avoid floating-point rounding issues you can compare value * n against sum (integer math), but watch for overflow — use a wider integer type if necessary. Check scanf return values when reading input and avoid magic numbers by using a named constant or a variable for the array length. Finally, decide whether values exactly equal to the average should be counted or reported separately; the current code ignores them.

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.