C++ Program to Find Average of Numbers

C++ Program to Find Average of Numbers

Calculating the average, or mean, of numbers is one of the most common tasks in programming. In C++, this exercise not only helps beginners understand loops and input/output operations but also introduces them to functions, arrays, vectors, and even modern STL algorithms. Finding the average is widely used in statistics, data analysis, and real-world applications like calculating test scores or financial data. In this article, we’ll explore multiple methods to calculate the average of numbers, starting from simple loops to modern C++ approaches.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Program 1: Using Basic Loop

This is the simplest approach where we take inputs from the user, sum them using a loop, and then divide by the total count to find the average.

#include <iostream>

using namespace std;

int main() {

    int n;

    cout << "Enter the number of elements: " << endl;
    cin >> n;

    double sum = 0, num;

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

        cout << "Enter number " << i+1 << ": " << endl;
        cin >> num;
        sum += num;

    }

    double average = sum / n;

    cout << "The average is " << average << endl;

    return 0;

}

This program works by initializing a sum variable and adding each input number to it. Dividing the total sum by the number of elements gives the average. Beginners can learn how loops, variables, and basic arithmetic work together in C++.

Program 2: Using an Array

Storing the numbers in an array can help in cases where you might need the numbers for later use, not just for computing the average.

#include <iostream>

using namespace std;

int main() {

    int n;

    cout << "Enter the number of elements: " << endl;
    cin >> n;

    double numbers[n], sum = 0;

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

        cout << "Enter number " << i+1 << ": " << endl;
        cin >> numbers[i];
        sum += numbers[i];

    }

    double average = sum / n;
    cout << "The average is " << average << endl;

    return 0;

}

Here, an array stores the input numbers. Summing the array elements provides the total, and dividing by n calculates the average. This approach introduces beginners to arrays and indexed access.

Program 3: Using Functions

Encapsulating the average calculation in a function makes the code modular and reusable.

#include <iostream>

using namespace std;

double calculateAverage(double numbers[], int n) {

    double sum = 0;

    for(int i = 0; i < n; i++) {
        sum += numbers[i];
    }

    return sum / n;

}

int main() {

    int n;

    cout << "Enter the number of elements: " << endl;
    cin >> n;

    double numbers[n];

    for(int i = 0; i < n; i++) {
        cout << "Enter number " << i+1 << ": " << endl;
        cin >> numbers[i];
    }

    double average = calculateAverage(numbers, n);
    cout << "The average is " << average << endl;

    return 0;

}

Using a function calculateAverage separates the logic from the main program. This helps beginners learn about functions, parameter passing, and code reusability.

Program 4: Modern STL Approach with Vectors

Modern C++ allows using the Standard Template Library (STL) to simplify operations. Here, we use a vector to store numbers and std::accumulate to calculate the sum efficiently.

#include <iostream>
#include <vector>
#include <numeric> // for std::accumulate

using namespace std;

double calculateAverage(const vector<double>& numbers) {

    double sum = accumulate(numbers.begin(), numbers.end(), 0.0);
    return sum / numbers.size();

}

int main() {

    int n;

    cout << "Enter the number of elements: " << endl;
    cin >> n;

    vector<double> numbers(n);

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

        cout << "Enter number " << i+1 << ": " << endl;
        cin >> numbers[i];

    }

    double average = calculateAverage(numbers);
    cout << "The average of the entered numbers is " << average << endl;

    return 0;

}

In this version, std::vector stores the inputs dynamically, and std::accumulate calculates the sum in one line. This approach is clean, modular, and scalable. Beginners can learn about vectors, STL algorithms, and modern C++ coding practices.

Program 5: Using Predefined Dataset

Sometimes, you may want to calculate the average of a known dataset without asking the user for input. This method is simple and good for testing or fixed data.

#include <iostream>
#include <vector>
#include <numeric> // for std::accumulate

using namespace std;

double calculateAverage(const vector<double>& numbers) {

    double sum = accumulate(numbers.begin(), numbers.end(), 0.0);
    return sum / numbers.size();

}

int main() {

    // Predefined dataset
    vector<double> numbers {12.5, 15.0, 20.5, 10.0, 18.0};

    double average = calculateAverage(numbers);
    cout << "The average of the predefined dataset is " << average << endl;

    return 0;

}

In this program, the numbers are stored directly in a vector. The std::accumulate function calculates the total sum, and dividing by the size of the vector gives the average. Beginners can see how easy it is to work with predefined data and how functions help keep the code organized and reusable. This approach is particularly useful for testing and learning without needing to type input each time.

Program 6: Using Recursion

Recursion is a programming technique where a function calls itself to solve smaller parts of a problem. Here, we calculate the sum of a dataset recursively to find the average.

#include <iostream>
#include <vector>

using namespace std;

// Recursive function to calculate sum
double recursiveSum(const vector<double>& numbers, int index) {

    if(index < 0) return 0; // Base case: no elements left
    return numbers[index] + recursiveSum(numbers, index - 1);

}

int main() {

    // Predefined dataset
    vector<double> numbers {12.5, 15.0, 20.5, 10.0, 18.0};

    double sum = recursiveSum(numbers, numbers.size() - 1);
    double average = sum / numbers.size();

    cout << "The average calculated recursively is " << average << endl;

    return 0;

}

In this program, recursiveSum adds the last element of the vector to the sum of all previous elements. This process continues until it reaches the first element, which serves as the base case. Beginners can see how recursion breaks a problem into smaller parts and can apply this idea to other tasks like factorials, Fibonacci numbers, or sum of digits. Recursion is not always the most efficient for large datasets, but it’s an excellent learning tool for understanding problem decomposition.

Program 7: Using for_each

The for_each algorithm applies a function to each element in a container. Here, we use it to calculate the sum of a dataset, then compute the average.

#include <iostream>
#include <vector>
#include <algorithm> // for std::for_each

using namespace std;

int main() {

    // Predefined dataset
    vector<double> numbers {12.5, 15.0, 20.5, 10.0, 18.0};
    double sum = 0;

    for_each(numbers.begin(), numbers.end(), [&](double n) {
        sum += n;
    });

    double average = sum / numbers.size();
    cout << "The average calculated using for_each is " << average << endl;

    return 0;

}

This program shows how for_each eliminates the need for explicit loops. Beginners can see how lambda functions make operations concise while still iterating over all elements.

Program 8: Using reduce

The reduce algorithm (C++17) allows efficient summation of elements, often optimized internally for parallel computation. It’s a modern and powerful way to compute aggregates like sums.

#include <iostream>
#include <vector>
#include <numeric> // for std::reduce

using namespace std;

int main() {

    // Predefined dataset
    vector<double> numbers {12.5, 15.0, 20.5, 10.0, 18.0};

    double sum = reduce(numbers.begin(), numbers.end(), 0.0);
    double average = sum / numbers.size();

    cout << "The average calculated using reduce is " << average << endl;

    return 0;

}

Using reduce is elegant and concise, and it highlights modern C++ capabilities. It’s particularly useful for large datasets because some implementations can parallelize the computation, providing better performance than a simple loop.

Frequently Asked Questions (FAQ)

Here are some common questions beginners ask about calculating averages in C++:

Q1: Can I use int instead of double for average?
Using int will truncate decimal values. For accurate averages, always use float or double.

Q2: What is the difference between for_each and reduce?
for_each applies a function to each element and is general-purpose, while reduce specifically aggregates values (like summing) and can be optimized internally.

Q3: Can I compute the average recursively for a vector instead of an array?
Yes, but you need to pass iterators or indices to handle vector elements recursively.

Q4: Is there a maximum number of elements I can use?
Practically, you are limited by memory. For very large datasets, using vectors and algorithms like reduce is more efficient.

Conclusion

Calculating averages in C++ teaches essential programming concepts like loops, arrays, vectors, recursion, and modern algorithms. We explored five methods: a basic loop with user input, a predefined dataset, recursion, for_each, and reduce. Beginners can start with simple loops, then experiment with recursion and modern algorithms for more efficient and elegant solutions. Practicing these methods strengthens both programming and problem-solving skills.

Additional & References

For beginners wanting to dive deeper into modern C++:

Scroll to Top