C I cant figure this program out in the simpliest way possib

C++

I can´t figure this program out in the simpliest way possible using while and if statements

Write a program to read data from input file. The first value read is the number of numbers to be read next. Calculate average of those numbers and write to an output file the numbers read and the average. Repeat this process until end of file. Use eof member function,

NAME YOUR FILE \" lab4input.dat\" for input file

\"lab4output.dat\" for output file

Input file:

4   12 14   99   83 5 2 9 56   4   3   2   13   15   1   6   8    32   12    3   4   5   12   34   45

Output file:
12 14 99 83
Number of numbers read = 4
The Average is 52

2 9 56 4 3
Number of numbers read = 5
The Average is 14.8

13 15
Number of numbers read = 2
The Average is 14

6
Number of numbers read = 1
The Average is 6

32 12 3 4 5 12 34 45
Number of numbers read = 8
The Average is 18.375

Solution

// C++ code

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

int main ()
{
int n;
double number;
// open file
ifstream inputFile (\"lab4output.dat\");
ofstream outputFIle (\"lab4output.dat\");

if (inputFile.is_open())
{
    while (inputFile >> n )
    {
      double average = 0;
      for (int i = 0; i < n; ++i)
      {
         inputFile >> number;
         average = average + number;
         outputFIle << number << \" \";
      }

      outputFIle << \"\ Number of numbers read = \" << n << endl;
      average = average/n;
      outputFIle << \"The Average is \" << average << endl << endl;

    }
    inputFile.close();
}

else cout << \"Unable to open file\";

outputFIle.close();
return 0;
}

/*
lab4output.dat

12 14 99 83
Number of numbers read = 4
The Average is 52

2 9 56 4 3
Number of numbers read = 5
The Average is 14.8

13 15
Number of numbers read = 2
The Average is 14

6
Number of numbers read = 1
The Average is 6

32 12 3 4 5 12 34 45
Number of numbers read = 8
The Average is 18.375

*/

C++ I can´t figure this program out in the simpliest way possible using while and if statements Write a program to read data from input file. The first value re
C++ I can´t figure this program out in the simpliest way possible using while and if statements Write a program to read data from input file. The first value re

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site