C++ Manually create a file Numbers.txtand fill it with integers, one below the o
ID: 3683354 • Letter: C
Question
C++
Manually create a file Numbers.txtand fill it with integers, one below the other. Write a program that reads ANY sequence of integers (can be positive, 0 or negative) from this file. Using a looping construct, you will read numbers from the file till end of the file is reached. Calculate the largest and the smallest numbers among the data in the file. Your code must display both of those on the terminal screen along with total count of numbers present in the sequence and the average (always print two digits after decimal point) of all numbers in the file.
Count =
Average =
Largest Value =
Smallest Value =
Note: Keep in mind that the file can have any number of integers and the count can only be determined by reading the entire file.
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream input;
char filename[10];
cout<<"Enter filename: ";
cin>>filename;
input.open(filename);
int max;
int min;
int count = 0;
double total = 0;
int num;
//reading file
while(input>>num){
if(count == 0){ // reading first number
max = num;
min = num;
}
else{
if(max < num)
max = num;
if(min > num)
min = num;
}
total = total + num;
count++;
}
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
cout<<"Total count: "<<count<<endl;
cout<<"Average: "<<total/count<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.