I have this code and I have to do two things. One id to get the numbers from a file that has already been made. Two is to make each problem into a function. Such as a function for getting the minimum number and a function to get the highest number. If I could get help with at least the one to make each one a function, I will be very thankful.
#include<iostream>
usingnamespace std;
int main()
{
int arr[10], n, i, max, min;
cout << "Enter the size of the array : ";
cin >> n;
cout << "Enter the elements of the array : ";
for (i = 0; i < n; i++)
cin >> arr[i];
max = arr[0];
for (i = 0; i < n; i++)
{
if (max < arr[i])
max = arr[i];
}
min = arr[0];
for (i = 0; i < n; i++)
{
if (min > arr[i])
min = arr[i];
}
cout << "Largest element : " << max;
cout << " Smallest element : " << min;
cout << "\n\n";
system("pause");
return 0;
}
#include <iostream>
#include <vector>
#include <fstream>
#include <climits>
// get the numbers from a file that has already been made.
// vector: https://cal-linux.com/tutorials/vectors.html
std::vector<int> get_numbers_from( std::istream& file )
{
std::vector<int> array ;
int number ;
while( file >> number ) // for each number read from the input stream
array.push_back(number) ; // add it to the array
return array ;
}
int smallest_number_in( const std::vector<int>& numbers )
{
int min_value = INT_MAX ; // http://www.cplusplus.com/reference/climits/
// range based loop: http://www.stroustrup.com/C++11FAQ.html#forfor( int value : numbers ) if( value < min_value ) min_value = value ;
return min_value ;
}
int largest_number_in( const std::vector<int>& numbers )
{
int max_value = INT_MIN ; // http://www.cplusplus.com/reference/climits/for( int value : numbers ) if( value > max_value ) max_value = value ;
return max_value ;
}
void process_file( constchar file_name[] )
{
if( std::ifstream file{file_name} ) // if the file was successfully opened
{
const std::vector<int> numbers = get_numbers_from(file) ;
if( !numbers.empty() ) // if at least one number was read from the file
{
std::cout << numbers.size() << " numbers were read\n"
<< "smallest: " << smallest_number_in(numbers) << '\n'
<< "largest: " << largest_number_in(numbers) << '\n' ;
}
else std::cout << "no numbers were read from the file\n" ;
}
else std::cout << "failed to open file " << file_name << " for input\n" ;
}
int main()
{
constchar file_name[] = "numbers.txt" ;
process_file(file_name) ;
}