32.9k views
1 vote
Number Analysis Program: Write a program that reads data from the text file numbers.txt. Assume the file contains a series of numbers, each written on a separate line. The program should read the numbers from the file and store them into the array numbers. Then program should display the lowest value, the highest value in the array. Also calculate and display the average of these values.

User Blue Toque
by
6.0k points

1 Answer

1 vote

Answer:

See Explaination

Step-by-step explanation:

#include <iostream>

#include <fstream>

#include <string>

#include <iomanip>

// namespace std

using namespace std;

// start of the main function

int main() {

// setting precision to 2 decimal point

cout << fixed << setprecision(2) << endl;

// variable declration

int i, count = 0;

int min, max, value, arr[100];

double sum = 0;

double Avg;

// file object creation

ifstream infile;

string file;

// input the file name to read

cout << "Please enter the name of the file to read numbers for Number "

"Analysis program "

<< endl;

getline(cin, file);

infile.open(file.c_str());

// check if file exist or not

// and loop untill you get correct file name

// if you do not want to loop again and again then

// simply return 0; from code

if (infile.fail()) {

cout << "Error opening the file." << endl;

return 0;

// cout << "Please enter the name of the file to read numbers for Number "

// "Analysis program "

// << endl;

// getline(cin, file);

// infile.open(file.c_str());

}

// start reading the data from the file

while (infile >> value) {

arr[count] = value;

count++;

}

// initialize min max to arr[0]

min = max = arr[0];

// find the lowest element

for (i = 0; i < count; i++) {

if (arr[i] < min) {

min = arr[i];

}

}

for (i = 0; i < count; i++) {

// find the highest element

if (arr[i] > max) {

max = arr[i];

}

}

for (i = 0; i < count; i++) {

// calculate sum

sum = sum + arr[i];

}

Avg = sum / count;

// display output

cout << "The highest value is " << max << endl;

cout << "The lowest value is " << min << endl;

cout << "The sum of the numbers is " << sum << endl;

cout << endl;

cout << "The average of the numbers is " << Avg << endl;

return 0;

} // end of the main program