Calculate the Average of Array Elements

Calculate the Average of Array Elements in C++

In this exercise, you will create a program that calculates the average of the elements in an array. This is a common task when working with arrays, especially in data analysis, where calculating averages is often required.

The goal is to sum all the elements in the array, divide the sum by the total number of elements, and return the result as the average. This exercise will help you practice working with arrays and basic mathematical operations in C++.

Logic Components

1. Accumulation

We initialize a sum variable (usually double) to accumulate the values of all elements through a loop.

2. Precision

We use the double data type for the sum and the return value to ensure the division includes decimal points.

3. Division

The average is calculated by dividing the total sum by the size of the array.

Learning Objectives

  • 1. Declare and initialize an integer array with sample data.
  • 2. Create a modular function calculateAverage to handle the logic.
  • 3. Practice the search pattern using conditional loops.
  • 4. Output the search result clearly in the console.

Solution Implementation

average_array.cpp Algorithms
#include <iostream>
using namespace std;

// Function to calculate the average of the elements in the array
double calculateAverage(int arr[], int size) {
    double sum = 0; // Initialize a variable to store the sum of the elements
    
    // Loop through the array to sum all the elements
    for (int i = 0; i < size; i++) {
        sum += arr[i]; // Add each element to the sum
    }
    
    return sum / size; // Return the average (sum divided by the number of elements)
}

int main() {
    // Define an array of numbers
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array

    // Call the function to calculate the average
    double average = calculateAverage(numbers, size);

    // Print the result
    cout << "The average of the array elements is: " << average << endl;

    return 0;
}

Console Output:

The average of the array elements is: 30
Related Topics
Linear Search Conditional Iteration Function Return Codes Index Management

Share this Training

Help your friends learn C++ array logic!

© C++ Programming Exercises. Master the art of performance coding.