# avrage and sum of array

Discussion in 'C' started by hnaya, Dec 1, 2008.

1. ### hnayaNew Member

Joined:
Nov 29, 2008
Messages:
9
3
Trophy Points:
0
this is program to find average and sum of array

is my program correct ??

PHP:
``` #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); } ```

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
0
Occupation:
Senior Support Engineer
Location:
England
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?

3. ### TriG0rZNew Member

Joined:
Oct 2, 2008
Messages:
88
0
Trophy Points:
0
Location:
UK
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.

4. ### back from retirementNew Member

Joined:
Nov 9, 2008
Messages:
72
1
Trophy Points:
0
Occupation:
Student, UG 1st Yr., Jadavpur University
Location:
Uttarpara, West Bengal, India
@ 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???

Last edited: Dec 2, 2008
5. ### back from retirementNew Member

Joined:
Nov 9, 2008
Messages:
72
1
Trophy Points:
0
Occupation:
Student, UG 1st Yr., Jadavpur University
Location:
Uttarpara, West Bengal, India
@ 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....

Joined:
Oct 2, 2008
Messages:
88