PLease code a C++ program that prompts a user to enter 10 numbers. this program should read the numbers into an array and find the smallest number in the list, the largest numbers in the list the sum of the 10 numbers and the average of the 10 numbers please use file i/o and input measures for Handling Errors in C++ When Opening a File
Code:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
float numbers[10],sum = 0,smallest,largest,average,x;
ifstream inFile;
int i=0;
inFile.open("test.txt"); //open input file
if (!inFile) {
cout << "Unable to open file"; //if file will not open
exit(1); // terminate with error
}
else //if file sucessfully open
{
while (inFile >> x) //read 10 numbers from file and store in array
numbers[i++]=x;
}
smallest=numbers[0]; //Consider first element as smallest
largest=numbers[0]; //Consider first element as largest
for(i=0;i<10;i++)
{
sum=sum+numbers[i]; //calculate sum of the numbers
if (numbers[i] < smallest) //find smallest number
smallest = numbers[i];
if (numbers[i] > largest) //find largest number
largest = numbers[i];
}
average=sum/10; //calculate average
inFile.close(); //close the input file
//print outputs
cout << "Smallest number = " << smallest << endl;
cout << "Largest number = " << largest << endl;
cout << "Sum = " << sum << endl;
cout << "Average = " << average << endl;
return 0;
}
Input file
Output:
Get Answers For Free
Most questions answered within 1 hours.