Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   avrage and sum of array (http://www.go4expert.com/forums/avrage-sum-array-t15311/)

 hnaya 1Dec2008 21:57

avrage and sum of array

this is program to find average and sum of array

is my program correct ??

PHP Code:

``` #include<stdio.h> #include<conio.h> void main() { int a[5]; int i,sum=0,n; float avg; clrscr(); printf("Enter the array elemtns\n"); for (i=0;i<5;i++) scanf("%d",&a[i]); for (i=0;i<5;i++) { sum=sum+a[i]; avg=(float)sum/n; } printf("\n sum of array elements ===%d",sum); printf("\n average of array elements === %f",avg); }  ```

 xpi0t0s 2Dec2008 04:08

Re: avrage and sum of array

Well, you tell us. Does it print the sum and the average? If it does, then why do you think it might not be?
If you enter 5,10,15,20,25, the average should be 15 and the sum 75. Do you get those results or something else?

 TriG0rZ 2Dec2008 18:14

Re: avrage and sum of array

every time i run it i get an error which is weird so i dunno if its my but do what xpi0t0s said cause you know hes right lol.

It does seem abit.... werid cause ive done this but i did it a diffrent way. Where the user just input 6 values i then would use scanf to get those values then at the end do g=a+b+c+d+e+f for sum and then do g/6.0=your average.

 back from retirement 2Dec2008 18:52

Re: avrage and sum of array

@ hnaya....Cast a look on this line....
Code:

`avg=(float)sum/n;`
what is "n" here???

I think the problem you are facing is that the sum is okk...but you found the average to be troublesome....am I right???

 back from retirement 2Dec2008 18:57

Re: avrage and sum of array

@ TriG0rZ.....what you are doing is that you know there is six values to come....what if there are 66 values??? Surely you aren't gonna use 66 scanf's for them...and not as well 66 variables to declare and your sum= a1+ a2+ a3+ .....a66....you will simply become crazy!!!....that's what the array is for...

You can use for loop to get all the values with just one scanf and again a for loop to get their sum as well....

 TriG0rZ 2Dec2008 22:34

Re: avrage and sum of array

Quote:
 Originally Posted by back from retirement (Post 39747) @ TriG0rZ.....what you are doing is that you know there is six values to come....what if there are 66 values??? Surely you aren't gonna use 66 scanf's for them...and not as well 66 variables to declare and your sum= a1+ a2+ a3+ .....a66....you will simply become crazy!!!....that's what the array is for... You can use for loop to get all the values with just one scanf and again a for loop to get their sum as well....
yep what you said is 100% true and i never thought about that one lol so thanks :)

 All times are GMT +5.5. The time now is 17:23.