avrage and sum of array

hnaya's Avatar
Light Poster
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's Avatar, Join Date: Aug 2004
Mentor
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's Avatar, Join Date: Oct 2008
Contributor
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's Avatar, Join Date: Nov 2008
Contributor
@ 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 by back from retirement; 2Dec2008 at 19:02..
back from retirement's Avatar, Join Date: Nov 2008
Contributor
@ 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's Avatar, Join Date: Oct 2008
Contributor
Quote:
Originally Posted by back from retirement View Post
@ 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