Write a program that opens a text file called numberstxt for

Write a program that opens a text file called \"numbers.txt\" for reading. The file contains a sequence of integers all separated by new lines. Your program should read all of the numbers in the file and output the following information: (1) A count of the number of integers read; (2) the sum of all the integers in the file; (3) the smallest integer in the file; (4) the largest integer in the file; and (5) the average of all the numbers. You may NOT assume there are 11 integers in the file. The program should work for arbitrary number of integers and arbitrary of inputs, so you should test for various inputs (e.g., all are positive numbers, all are negative numbers). You may assume that only integers are in the file though. You do not need nor may you use arrays for this program.

Solution

Did not mention program in which language. Done in c++

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
   ifstream input;
   int min=0,max=0,num=0,sum=0,cnt=0;
   float avg=0;
   input.open(\"numbers.txt\");
   if(input.fail())
   {
       cout<<\"Cant open file \"<<endl;
       exit(1);
   }
   while(!input.eof())
   {
       input>>num;
       if( cnt == 0 )
           min;
       if( num < min)
           min = num;
       if( num > max)
           max = num;
       sum+=num;
       cnt++;
   }
   avg = (float)(sum)/(cnt);

   cout<<\"Number of integers read: \"<<cnt<<endl;
   cout<<\"Sum of integers: \"<<sum<<endl;
   cout<<\"Smallest integer: \"<<min<<endl;
   cout<<\"Largest integer: \"<<max<<endl;
   cout<<\"Average of all integers: \"<<avg<<endl;
}

 Write a program that opens a text file called \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site