Calculate average in c programming using arrays

Explanation: 

We will solve this problem using array. Because, without array we need to take user input for n numbers again and again by using printf () and scanf () functions for n times each. But in case of array, just we need to initialize the array size and run a for loop from 0 to n-1.

  • Formula to find the average of n numbers is :     sum of n numbers / n;
In this c program we will first initialize float sum = 0; and for each array elements we will add array[i] with sum till n-1.



CODE STARTS HERE :
  1. #include<stdio.h>
  2. int main()
  3. {
  4.     int n;
  5.     printf("For how many numbers you want average?\n");
  6.     scanf("%d",&n);
  7.     int nums[n];
  8.     float sum=0;
  9.     printf("Enter the numbers : \n");
  10.     for(int i=1;i<=n;i++)
  11.     {
  12.         printf("Enter %d number: \n",i);
  13.         scanf("%d",&nums[i]);
  14.         sum=sum+nums[i];
  15.     }
  16.     float avg=sum/(float)n;
  17.     printf("The average is: %f\n",avg);
  18.     return 0;
  19. }

INPUTS AND OUTPUTS:


For how many numbers you want average?
4
Enter the numbers :
Enter 1 number:
11
Enter 2 number:
12
Enter 3 number:
12
Enter 4 number:
22
The average is: 14.250000
Post a Comment (0)
Previous Post Next Post