Program to Find Average using Array
Average :
Average is defined as sum of given numbers divided by total number of entities. We will write a Program to find average of numbers.
Working of Program :
In the program, we will take array of n elements and find the average of the array.
Run
#include<stdio.h> int main() { int arr[10] = {2,3,4,54,65,34,23,34,123,80}; int sum=0, average; for(int i=0;i<10;i++){ sum += arr[i]; } average = sum/10; printf("The average of given numbers : %d", average); return 0; }
Output :
The average of given numbers : 42
In the above program,
- We take the array of size 10 also initialize those elements.
- In the for loop, sum of these 10 elements is calculated.
- Average will be calculated by sum/10.
- printf will print the output on the screen
Example :
Let’s solve same problem by taking number of elements and elements from user
Run
#include<stdio.h> int main() { int arr[100], n,sum =0; printf("Enter number of elements you want to find average:"); scanf("%d", &n); for(int i=0;i < n;i++){ printf("Enter single element %d:", i+1); scanf("%d", &arr[i]); } float average; for(int i=0;i < n;i++){ sum += arr[i]; } average = sum/n; printf("The average of elements is : %f", average); return 0; }
Output :
Enter number of elements you want to find average: 6 Enter single element 1:4 Enter single element 2:65 Enter single element 3:34 Enter single element 4:44 Enter single element 5:22 Enter single element 6:12 The average of elements is : 30.000000
What Happened Above?
In the above program, we take numbers from the users and store them in the array and by using for loop find the sum of all elements and finally find the average by dividing the sum by number of elements.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment