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 reads in an array of type int. The program pro

ID: 3809734 • Letter: W

Question

Write a complete C++ program that reads in an array of type int. The program provides facility to either read an array from the keyboard or from a file, at the user's choice. If the user chooses file input, the program should request a file name. You may assume that there are less than 100 entries in this array. Your program determines how many entries there are. In addition, the program should also find the maximum number in the array and calculates the average of the array. You are required to use functions.

Explanation / Answer

#include <iostream>
#include <fstream>
using namespace std;
int maxCalc(int array[], int size)
{
    int maxVal = array[0];
    for(int i = 1; i < size; i++)
        if(array[i] > maxVal)
            maxVal = array[i];
    return maxVal;      
}
double avgCalc(int array[], int size)
{
    double avg = 0;
    for(int i = 0; i < size; i++)
        avg += array[i];
    avg /= size;
    return avg;  
}
int readValuesFromFile(ifstream &fin, int array[])
{
    int size = 0;
    while(!fin.eof())
        fin >> array[size++];
    return size;  
}
int readValuesFromConsole(int array[])
{
    int size = 0;
    cout << "Enter the values, terminated by -1: ";
    cin >> array[size++];
    while(array[size-1] != -1)
        cin >> array[size++];
    return size-1;  
}
int main()
{
    int array[100];
    int inputSource;
    cout << "What is your source of input (1. File. 2. Console.): ";
    cin >> inputSource;
    int size = 0;
    if(inputSource == 1)
    {
       string fileName;
       cout << "Enter the name of the file to read from: ";
       cin >> fileName;
       ifstream fin;
       fin.open(fileName);
       size = readValuesFromFile(fin, array);
    }  
    else if(inputSource == 2)
    {
       size = readValuesFromConsole(array);
    }
    else
    {
       cout << "Invalid source choice..." << endl;
       return 0;
    }
    cout << "The maximum value in the array is: " << maxCalc(array, size) << endl;
    cout << "The average of values in the array is: " << avgCalc(array, size) << endl;
}

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