Number Analysis Program Write a program that asks the user for a file name. Assu
ID: 3681186 • Letter: N
Question
Number Analysis Program
Write a program that asks the user for a file name. Assume the file contains a series of
numbers, each written on a separate line. The program should read the contents of the
file into an array and then display the following data:
• The lowest number in the array
• The highest number in the array
• The total of the numbers in the array
• The average of the numbers in the array
If you have downloaded this book’s source code from the companion Web site, you
will find a file named numbers.txt in the Chapter 07 folder. You can use the file to
test the program. (The companion Web site is at www.pearsonhighered.com/gaddis .)
Explanation / Answer
/***** c++ Number Analysis Program *****/
#include <iostream>
#include <vector>
#include <stdio.h>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
string filename;
vector<int> numbers;
int data;
double sum = 0;
double avg ;
cout << "Enter Filename: ";
cin >> filename;
ifstream file_(filename.c_str());
// Keep reading in numbers
while(file_ >> data)
{
numbers.push_back(data);
// storing the elements in vector
}
// close file
file_.close();
int low = numbers[0];
int high = numbers[0];
for (int i = 0; i < numbers.size(); ++i)
{
sum = sum + numbers[i]; // calculating the total
if(numbers[i] > high) high = numbers[i]; // finding highest number
if(numbers[i] < low) low = numbers[i]; // finding lowest number
}
avg = sum / numbers.size();
cout << "The lowest number in the array is " << low << endl;
cout << "The highest number in the array is "<< high << endl;
cout << "The total of the numbers in the array is "<< sum << endl;
cout << "The average of the numbers in the array is "<< avg << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.