Sunday, July 12, 2009

Average and Sum of values in an array in C?

I am having a hard time getting The averages and sum from an array (weights[8]). I have the user input 8 differerent weights but having problems calc the average and total.. Can some one give me an example using C standard. Thnaks

Average and Sum of values in an array in C?
Maybe something like this:





#include %26lt;stdio.h%26gt;


#include %26lt;conio.h%26gt;





void main(){


int w[8]={1,2,3,23,8,6,7,8};/*Random Numbers*/


int i,sum=0,average;





clrscr();


for (i=0;i%26lt;8;i++){


sum+=w[i];


}


average = (sum/8);


printf("The sum is: %d\n And the average is: %d",sum,average);


getch();


clrscr();


}








}
Reply:int arr[] = {2,4,5,22,15,23,17,20};





int arrSize = sizeof(arr)/sizeof(int);





int total = 0, avg = 0;


for(int ii=0; ii %26lt; arrSize; ii++)


total += arr[ii];





avg = total / arrSize;





printf("Total = %d\n", total);


printf("Avg = %d\n", avg);
Reply:Probably you are trying to acess an ilegall memory reference. You CANNOT acess weights[8]. Just from 0 to 7. Got it?
Reply:http://www.cprogramming.com/tutorial/les...
Reply:for(x=0;x%26lt;8;x++) {


sum = sum + weights[x]


}


printf("Sum = %f", sum);


printf("Average = %f", sum/8);

floral deliveries

No comments:

Post a Comment