Calculate Average of Array Elements

Calculate Average of Array Elements

Easy C++ Arrays 25 views
Explanation Complexity

Problem Statement

Write a program that takes an array of numbers and calculates their average. This helps understand array traversal and basic arithmetic operations.

Logic: Sum all elements and divide by total count

Input Format

An integer n (size of array)
Then n integers.

Output Format

Average of the array elements.

Example

5
10 20 30 40 50
30

Constraints

• n ≥ 1

• Use integer or float as needed

Concept Explanation

Average is found by adding all elements and dividing by the total number of elements.

Step-by-Step Explanation

1.Read array size n.

2.Read all n elements into an array.

3.Initialize sum = 0.

4.Traverse the array from index 0 to n-1.

5.Add each element to sum.

6.Calculate average = sum / n.

7.Print the average.

Concept Explanation

Average is found by adding all elements and dividing by the total number of elements.

Step-by-Step Explanation

1.Read array size n.

2.Read all n elements into an array.

3.Initialize sum = 0.

4.Traverse the array from index 0 to n-1.

5.Add each element to sum.

6.Calculate average = sum / n.

7.Print the average.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers.
Output Format
Average of the array elements.
Constraints
• n ≥ 1

• Use integer or float as needed

Examples

Input:
5 10 20 30 40 50
Output:
30

Example Solution (Public)

C++
#include <iostream>
using namespace std;

void question1_array_average() {
    int marks[] = {85, 90, 78, 92, 88};
    int total = 0;
    int size = 5;
    
    for(int i = 0; i < size; i++) {
        total = total + marks[i];
    }
    
    float average = (float)total / size;
    cout << "Average marks: " << average << endl;
}

Official Solution Code

#include <iostream>
using namespace std;

void question1_array_average() {
    int marks[] = {85, 90, 78, 92, 88};
    int total = 0;
    int size = 5;
    
    for(int i = 0; i < size; i++) {
        total = total + marks[i];
    }
    
    float average = (float)total / size;
    cout << "Average marks: " << average << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.