C Program to Calculate the Sum and Average of an Array

In this article, we will write a C program that calculates the sum and average of an array.

The program first asks the user to enter the size of the array and then takes the array elements as input. The sum and average of the array elements is printed on the screen.

Sample Input:

Enter the size of the array: 5
Enter the array elements: 1 2 3 4 5

Sample Output:

Sum of array elements is: 15
Avg. of arrays elements is: 3.00

To calculate the sum and average of an array, we can initialize a variable sum to 0 and then use a for or a while loop to iterate through the given array and add each element of the array to the sum variable.

Then to calculate the average of the array, we can divide the calculated sum by the size of the array.

See the following implementation:

// C program to calculate the sum
// and avg. of array elements
#include <stdio.h>

int main(){
	
	int arr[100], size, sum;
	float avg;
	
	printf("Enter the size of the array: ");
	scanf("%d", &size);
	
	printf("Enter the array elements: ");
	for(int i = 0; i < size; i++){
		scanf("%d", &arr[i]);
	}
	
	// Set the initial sum to zero
	sum = 0;
	
	// Loop through the array to calculate the sum
	for(int i = 0; i < size; i++){
		sum = sum + arr[i];
	}
	
	// Calculate the avg
	avg = sum / size;
	
	printf("Sum of array elements is: %d", sum);
	printf("\nAvg. of arrays elements is: %.2f", avg);

    return 0;
    
}

Output:

Enter the size of the array: 5
Enter the array elements: 1 2 3 4 5
Sum of array elements is: 15
Avg. of arrays elements is: 3.00

Code Explanation:

  • The program defines an integer array arr with a maximum size of 100.
  • The program also defines an integer variable size to store the size of the array, a variable sum to store the sum of the elements, and a variable avg to store the average of the elements.
  • Prompts the user to enter the size of the array using printf() function and reads the input using scanf() function.
  • Initializes the sum variable to 0.
  • Calculates the sum of the elements by iterating through each element of the array using the for loop and adding the value of each element to the sum variable.
  • Calculates the average of the elements by dividing the sum variable by the size variable and assigning the result to the avg variable.
  • Prints the sum of the elements using printf and the %d format specifier.
  • The program also prints the average of the elements using printf and the %f format specifier with a precision of two decimal places using .2 before the f specifier.

That’s all for this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.