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

Reply

Join Date: Feb 2007
Posts: 31
Reputation: IwalkAlone is an unknown quantity at this point 
Solved Threads: 0
IwalkAlone IwalkAlone is offline Offline
Light Poster

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

 
0
  #1
May 16th, 2007
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!
Reply With Quote Quick reply to this message  
Join Date: May 2006
Posts: 38
Reputation: msvinaykumar is an unknown quantity at this point 
Solved Threads: 2
msvinaykumar msvinaykumar is offline Offline
Light Poster

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

 
0
  #2
May 16th, 2007
for(i=0;i<10;i++)
{
sum=sum+X[i];
}
calculate sum first then Average...
out of the for loop
avg=sum/10.0;
Reply With Quote Quick reply to this message  
Join Date: Dec 2005
Posts: 5,850
Reputation: Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute 
Solved Threads: 749
Team Colleague
Salem's Avatar
Salem Salem is offline Offline
Void main'ers are DOOMed

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

 
0
  #3
May 16th, 2007
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.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC