C++ Manually create a file Numbers.txtand fill it with integers, one below the o
ID: 3683261 • 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 <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
int data[1000];
infile.open("Numbers.txt");
if (!infile.is_open()) {
cerr<<"cannot open this file";
return 0;
}
int number,i=0,min,max,n,sum;
while(infile>>number)
data[i++] = number;
n = i;
if(n==0)
{
cout<<"Count = 0 Average = 0 Largest = Nil Smallest = Nil ";
return 1;
}
min = max = data[0];
sum = data[0];
for(i=1;i<n;i++)
{
if(min>data[i])
min = data[i];
if(max<data[i])
max = data[i];
sum += data[i];
}
cout<<"Count = "<<n<<endl;
cout<<"Average = "<<sum*1.0/n<<endl;
cout<<"Largest = "<<max<<endl;
cout<<"Smallest = "<<min<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.