Write a c++ program to accept 10 integers in an array and find its sum and average?
Write a c++ program to accept 10 integers in an array and find its sum and average?
Best answer
#include<iostream.h>
int main()
{
int arr[10];
int i,sum=0;
float avg;
cout<<"enter 10 number";
for(i=0;i<10;i++)
{
cin>>arr[i];
}
for(i=0;i<10;i++)
{
sum+=arr[i];
}
avg=sum/10;
cout<<"sum="<<sum<<endl;
cout<<"average="<<avg;
}Answer: Store the 10 integers in an array, add them in a loop, and divide the sum by 10.0 (not 10) to get the exact average.
#include <iostream>
using namespace std;
int main()
{
int arr[10], sum = 0;
float avg;
cout << "Enter 10 integers: ";
for (int i = 0; i < 10; i++) {
cin >> arr[i];
sum += arr[i];
}
avg = sum / 10.0f; // 10.0f avoids integer division
cout << "Sum = " << sum << endl;
cout << "Average = " << avg << endl;
return 0;
}Why 10.0f? If both sum and 10 are integers, sum / 10 is integer division and the decimal part is thrown away before the result is stored in avg. For example, numbers 1 to 10 give sum 55; 55 / 10 = 5, but the correct average is 5.5. Dividing by 10.0f (or writing (float)sum / 10) does floating-point division.
Standard C++ uses <iostream> with using namespace std;; the old <iostream.h> works only on Turbo C++.
Log in or create a free account to answer this question.