1. Introduction
Finding the average of a set of numbers is a fundamental operation in statistics and mathematics. In programming, this operation is typically performed using arrays or lists. In this blog post, we'll dive into a simple C++ program that computes the average of an array of numbers.
2. Program Overview
1. The user is prompted to input the size of the array.
2. The user then provides each number for the array.
3. The program sums up all the numbers.
4. The sum is then divided by the number of elements to compute the average.
5. Finally, the average is displayed.
3. Code Program
#include <iostream>
using namespace std;
int main() {
int n;
double sum = 0.0;
// Get number of elements from user
cout << "Enter the number of elements: ";
cin >> n;
double arr[n];
// Get array elements from user
cout << "Enter the elements of the array:" << endl;
for(int i=0; i<n; i++) {
cin >> arr[i];
sum += arr[i];
}
// Compute average
double average = sum / n;
// Display the average
cout << "Average of the array is: " << average << endl;
return 0;
}
Output:
Enter the number of elements: 5 Enter the elements of the array: 1 2 3 4 5 Average of the array is: 3
4. Step By Step Explanation
1. Array Initialization: The program starts by taking the number of elements and then reading each element into an array.
2. Summation: As the elements are read, they are added to a sum variable.
3. Compute Average: After reading all numbers, the average is computed by dividing the sum by the number of elements.
4. Result Display: The program outputs the computed average.
Through this program, you understand the basics of array manipulation in C++ and get an idea about a simple yet important statistical computation.
Comments
Post a Comment
Leave Comment