for(auto value : data)
cout << setw(6) << value;
cout << endl;
// Function returning a reference
double& lowest(double a, const int& len)
int j(0); // Index of lowest element
for(int i = 1; i < len; i++)
if(a[j] > a[i]) // Test for a lower value...
j = i; // ...if so update j
return a[j]; // Return reference to lowest element
I just need to learn how the for loop in the function works to find the lowest value in the array. Thank you in advance
1.Assume the first element in the array is both the smallest and the largest value.
2.)Compare the value of the second element with minimum and maximum values.
3.)If its larger give its value to maximum else if its smaller give its value to minimum.
4.)Continue to compare the element values with the values held by minimum and maximum. If less than minimum this will be the new value of minimum. Similarly if larger than maximum this will be the new value of maximum.
5.)When the loop ends minimum will hold the smallest value and maximum will hold the largest value.
In your loop minimum is j with the value of 0.
The function in question compares subsequently all elements in array with a minimum value, and if some element is less than the minimum value, it is updated. To start, the function assigns the minimum to be the first element (index is 0).
Imagine mother asks you to buy the smallest egg :) You go to the market, come to a desk, take the first egg and then start to compare it with second, third and so on. If any is smaller than the first, you return the first and keep that new as the smallest. Then continue with the remaining eggs.
serge you said the function assigns the minimum value to the first element index is 0, would that be the number three in this case. and also if that was the case you saying 3 is being compared with the other elements in the array. So is the function saying if 3 is larger than the other element update j for the lowest value. But isn't three larger than 2.7, but the complier doesn't update it to be the lowest value. Since I call the function twice in the code, the lowest value are 1.5 and 2.1. can you please clarify this for me, I would really appreciate it.
So that means that when the function finds 3.0 > 1.5, this updates j as the lowest value as 1.5. But the function keeps checking if it finds a lower value with 1.5 in hand. But in this case it doesn't so, it replaces data with 6.9. So is the way im looking at it is right or no?