943,962 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 2106
  • C RSS
May 16th, 2007
0

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

Expand Post »
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

  1.  
  2. #include<stdio.h>
  3. int main(void)
  4. {
  5. int X[10],i,lesser=0,greater=0,sum=0;
  6. float avg=0;
  7. for(i=0;i<10;i++)
  8. {
  9. printf("Enter number\n");
  10. scanf("%d",&X[i]);
  11. }
  12. for(i=0;i<10;i++)
  13. {
  14. sum=sum+X[i];
  15. avg=sum/10.0;
  16. if((float)X[i]>avg)
  17. {
  18. greater++;
  19. }
  20. else if((float)X[i]<avg)
  21. {
  22. lesser++;
  23. }
  24. }
  25. printf("Average of numbers is %f\n",avg);
  26. printf("sum of numbers is %d\n",sum);
  27. printf("No of elements greater than avg are %d and lesser are %d",greater,lesser);
  28. return(0);
  29. }

Everything works fine but the counts computed are both wrong.Please help!
Similar Threads
Reputation Points: 17
Solved Threads: 0
Light Poster
IwalkAlone is offline Offline
31 posts
since Feb 2007
May 16th, 2007
0

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

for(i=0;i<10;i++)
{
sum=sum+X[i];
}
calculate sum first then Average...
out of the for loop
avg=sum/10.0;
Reputation Points: 10
Solved Threads: 6
Light Poster
msvinaykumar is offline Offline
48 posts
since May 2006
May 16th, 2007
0

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

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.
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: help me
Next Thread in C Forum Timeline: Linked Lists in C





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC