I have to write functions (outside of main and then called in main) that compute
ID: 3850837 • Letter: I
Question
I have to write functions (outside of main and then called in main) that compute the high and low of integers entered by the user. This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int number, numInt;
cout << "How many integers would you like to test? ";
cin >> numInt;
for (int i = 0; i < numInt; i++)
{
cout << "Please enter an integer: " << endl;
cin >> number;
}
system("pause");
return 0;
}
Explanation / Answer
Hi,
The solution goes as follows:
1.) Create an array of integers of these numbers.
2.) create two methods one for computing the max and one for calculating the min of these integers and then call these two methods.
#include <iostream>
using namespace std;
int main()
{
int number, numInt;
cout << "How many integers would you like to test? ";
cin >> numInt;
//declare array of size number of integers you want to enter
int numarray[numInt];
for (int i = 0; i < numInt; i++)
{
cout << "Please enter an integer: " << endl;
cin >> number;
numarray[i] = number;
}
cout<<" The max number is: "<<getMax(numarray);
cout<<" The min number is: "<<getMin(numarray);
system("pause");
return 0;
}
int getMax(int array[]) {
int temp = array[0];
for (int i = 0; i < sizeof(array); i++) {
if(array[i] > temp) {
temp = array[i];
}
}
return temp;
}
int getMin(int array[]) {
int temp = array[0];
for (int i = 0; i < sizeof(array); i++) {
if(array[i] < temp) {
temp = array[i];
}
}
return temp;
}
One more solution will be as follows:
#include <iostream>
using namespace std;
int main()
{
int number, numInt;
cout << "How many integers would you like to test? ";
cin >> numInt;
for (int i = 0; i < numInt; i++)
{
cout << "Please enter an integer: " << endl;
cin >> number;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
system("pause");
return 0;
}