[SOLVED] Writing a function to find largest number from array in a text file

Issue

I can write a program to find the largest and smallest value in main, but I do not know how to do this in a separate function and for the numbers to be gotten from a file.My task is to enter numbers in an array which will be stored in a file and then the largest of those numbers needs to be found. I can write separate programs to do each, but I cannot combine them.

#include <iostream>
#include <fstream>
#include <ostream>
using namespace std;
int findLargest();

int main()
{
    ofstream outputFileStream("numbers.dat");

    int num;
    for (int i = 0; i < 5; i++)
    {
        cout << "please enter number to be written to file " << i << endl;
        cin >> num;
        outputFileStream << num << endl;

        cout << findLargest;
    
    }
}

int findLargest() {
    int numbers[5];
    int smallest = 0;
    int largest = 0;
    int temp = 0;

    for (int i = 0; i < 5; i++)
    {
        cout << "please enter numbers" << i + 1 << endl;
        cin >> numbers[i];
    }
    smallest = numbers[0];
    largest = numbers[0];

    for (int i = 1; i < 5; i++)
    {
        temp = numbers[i];
        if (temp > largest)
            largest = temp;
    }
    cout << "largest number is " << largest << endl;
}

Solution

There are sooo many ways to do this. Here’s one:

void Find_Largest(std::ostream& output_file)
{
    int smallest = 0;
    int largest  = 0;
    std::cout << "Please enter number 1:\n";
    std::cin >> smallest;
    largest = smallest;
    output_file << smallest << "\n";
    for (int i = 1; i < 5; ++i)
    {
        std::cout << "Please enter number " << i << "\n";
        int number;
        std::cin >> number;
        if (number < smallest) smallest = number;
        if (number > largest)  largest  = number;
        output_file << number << "\n";
    }
    std::cout << "Largest is:  " << largest << "\n";
    std::cout << "Smallest is: " << smallest << "\n";
}

int main()
{
    ofstream outputFileStream("numbers.dat");
    Find_Largest(outputFileStream);
    return 0;
}

In the above code, the output file is created in main and passed to the function Find_Largest.

The Find_Largest uses a running min and max algorithm. The numbers are written to the output file (that was passed to the function).

Answered By – Thomas Matthews

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.