Write a function find_min that takes a double pointer indicating the start of an array, and an int indicating the length of the array. It should return a pointer to the minimum number in the array. Fill in the "???"
#include <iostream>
using namespace std;
double* find_min(double* a, int n) {
???
}
int main() {
int n;
cin >> n;
double arr[100];
for (int i=0; i<n; i++) cin >> arr[i];
// call your function and save result
double* min_loc = find_min(arr, n);
cout << ...; // there is some hidden testing code here
cout << "Pointed-to value is " << *min_loc << endl;
// change that variable to 1000
*min_loc = 1000;
// run your code again
min_loc = find_min(arr, n);
cout << ...; // there is some hidden testing code here
cout << "Pointed-to value is " << *min_loc << endl;
}
To the question : You need a for loop to iterate though the array. You need a pointer to pinpoint the address whose stored value is the lowest.
1 2 3 4 5 6 7 8 9 10
double* find_min(double* a, int n)
{
double *p_min = a;
for(double *it = a + 1; it < &a[n]; it++)
{
// Something like that, do something with p_min
}
// Return the corresponding value
}
We assume p_min points to a value that is the lowest. As we iterate though the array, we will check if there is a value that is even lower than the current lowest value. If there is one we will make p_min point to the new address whose stored value is the lowest.
In fact, this can be expressed in just two simple statements. You only have one.