C++ Program to Calculate the Average of all the Elements Present in an Array

10/05/2024 0 By indiafreenotes

Creating a C++ program to calculate the average of all elements in an array involves initializing an array, computing the sum of its elements, and then dividing the sum by the number of elements to obtain the average. This is a fundamental concept that is frequently utilized in data analysis and statistics within programming.

Here’s a C++ program that demonstrates how to calculate the average of all the elements in an array:

#include <iostream>

int main() {

    // Define the array

    int arr[] = {10, 20, 30, 40, 50};

    int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    // Initialize sum

    int sum = 0;

    // Calculate the sum of all elements in the array

    for (int i = 0; i < n; i++) {

        sum += arr[i];

    }

Here’s how the program works:

  • The array arr is defined with some example values.
  • The size of the array is calculated using sizeof(arr) / sizeof(arr[0]).
  • The program initializes a variable sum to 0.
  • The for loop iterates through the array, adding each element’s value to sum.
  • After the loop completes, the average is calculated by dividing sum by the number of elements (n).
  • The program outputs the average of all the elements in the array.