GoogleTag

Google Search

[Programming] Question 5: Find the average of all elements in an array in C?

Learn how to write a C program to calculate the average of all elements in an array. This tutorial walks you through the process of summing the elements of an array, computing the average, and handling arrays in C. Ideal for those looking to understand basic array operations and arithmetic in C programming.

#include <stdio.h>

int main() {
	int arr[] = {1, 2, 3, 4, 5};
	int sum = 0;
	int avg;
	int i;

	for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
		sum += arr[i];
	}

	avg = sum / sizeof(arr)/sizeof(arr[0]);

	printf("Average of array elements: %d\n", avg);

	return 0;
} 
Explanation:

Inside the main() function:

- An integer array arr is declared and initialized with values.

- An integer variable sum is initialized to zero to store the sum of array elements.

- An integer variable avg is declared to store the average.

- A for loop is used to iterate through each element of the array.

- Within the loop, each element of the array is added to the sum.

- After the loop, the average is calculated by dividing the sum by the number of elements in the array.

- Finally, the average of array elements is printed to the console.

 

Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts