Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete C++ program that will do the following: a) Read integers, one p

ID: 3674005 • Letter: W

Question

Write a complete C++ program that will do the following: a) Read integers, one per line, from a file called integers.dat. The integers in the file can be positive, negative, or 0. There are at most 125 positive integers (may be less) in the file. Store the positive integers only in an array. b) Output the positive integers to a file called positiveIntegers.dat in reverse sequence (the first integer in the array should be the last one written to the file). c) Write a function that has the array as one of the parameters and returns the average of the positive integers. d) Display on the output screen, with appropriate labels, the number of positive integers and the average of the positive integers.

Explanation / Answer

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

double average (int a[] , int n)                // function to calculate average
{
    double sum = 0;
    for (int j = 0; j < n; j++)
    {
        sum = sum + a[j];
    }

    sum = sum /n;
    return sum;
}


int main()
{
    int arr[125];                             // setting 125 s maximum length of array can be 125
    ifstream file_("integers.dat");             // opening integers.dat

    int i = 0;
    int number;

    while(file_ >> number)
    {
        if(number > 0)
        {
        arr[i] = number;                   // putting positive integers into array 1
        i++;
        }
      
    }
   
    file_.close();                          // closing integers.dat
  

    double average_of_positive_numbers = average ( arr, i); // calling the function
                                                              // to calculate average

    ofstream file("positiveIntegers.dat");    // opening file positiveintegers.dat
    for ( int j = 0; j < i; j++)
    {
        file << arr[i-j-1];                  // putting numbers of arra2 which are in reverse order
        file << " ";
    }
    file.close();                         // closing positiveintegers.dat

    printf("There are %d positive Integers in integers.dat ",i);
    printf("Average of positive Integers is %f ",average_of_positive_numbers);

    return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote