Find the average of n numbers with while & for loop [ C program Code]

This C Program Code finds the average of n numbers. Here we have used two different methods to solve the problem - i.e the WHILE loop and FOR loop.


Using WHILE loop

#include<stdio.h>
int main()
{
int n,i=0,sum=0,num;
float avg;
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter the numbers: ");
while(i<n)
{
scanf("%d",&num);
sum=sum+num;
i=i+1;
}
avg=(float)sum/n;
printf("The average is %f",avg);
getch();
return(0);
}
view raw gistfile1.txt hosted with ❤ by GitHub
Using FOR loop

#include<stdio.h>
int main()
{
int n,i,sum=0,num;
float avg;
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter the numbers: ");
for(i=0;i<n;i++)
{
scanf("%d",&num);
sum=sum+num;
}
avg=(float)sum/n;
printf("The average is %f",avg);
getch();
return(0);
}
view raw gistfile1.txt hosted with ❤ by GitHub

Comments