OneBite.Dev - Coding blog in a bite size

Find The Average Of All Elements In An Array In C++

Code snippet for how to Find The Average Of All Elements In An Array In C++ with sample and detail explanation

C++ is a very versatile and capable programming language that caters to several mathematical operations with relative ease. Amongst these operations is the ability to find the average of all elements present in an array, a topic we will delve into in this quick guide.

Code Snippet for Finding the Average of All Elements in an Array

Below is the code snippet that demonstrates how to find the average of all elements in an array in C++:

#include <iostream>
using namespace std;

int main()
{
    int numArray[5] = {10, 20, 30, 40, 50};
    int sum = 0;
    for (int i = 0; i < 5; i++)
    {
        sum += numArray[i];
    }
    double average = sum / 5.0;
    cout << "The average of all elements in the array is " << average << endl;
    return 0;
}

Code Explanation for Finding the Average of All Elements in an Array

This C++ code snippet has several components that work together to calculate the average of all array elements. Here is the step-by-step explanation:

  1. Includes necessary header files: The #include <iostream> directive is included at the top of the program as it is required for utilizing input and output operations.

  2. Declares an array: An array ‘numArray’ of 5 elements is declared with values of each element (10, 20, 30, 40, 50).

  3. Initializes a variable: The integer variable ‘sum’ is initialized with zero. This variable will hold the sum of all the elements of the array.

  4. Applies the ‘for’ loop: A ‘for’ loop is used to traverse through the elements of an array. It starts from ‘0’ (as array index in C++ starts from 0), and continues till ‘5’ (as there are 5 elements in the array). With each iteration, the value of the currently indexed number in the array is added to the variable ‘sum’.

  5. Calculates the average: Outside the loop, the average is calculated by dividing the sum of all elements by the total number of elements. The result is stored in a double-precision floating-point variable - ‘average’. The division by 5.0 (not 5) ensures that the result of the division is in decimal form.

  6. Prints out the result: The computed average is then printed out on the screen using the ‘cout’ statement.

  7. Ends the program: The ‘return 0’ statement marks the successful termination of the program.

This technique can be expanded to larger arrays and can also be modified to accommodate dynamic and user input arrays in C++. Remember to carefully handle the indexing and size specification of the array to prevent errors or unexpected results.

c-plus-plus