John J wrote:
Karl,
As I said in the other thread thanks but your code doesn't work inside my
class
compare what I posted with the thing you posted.
You didn't use what I posted. You used something
that looks close.
If you need to understand something, then a seperate
test program which just concentrates on the topic
you want to understand is sometimes a good idea.
#include <iostream>
int main()
{
int Numbers[] = { 3, 8, 2, 5, 6 };
int Smallest;
Smallest = Numbers[0];
for( int i = 1; i < 5; i++ )
{
if( Numbers[i] < Smallest )
Smallest = Numbers[i];
}
std::cout << "The smallest number was " << Smallest << std::endl;
return 0;
}
This does exactly the same thing: find the smallest (best)
number in an array of numbers. Use this program and step
it through with your debugger. Understand how it does, what
it does. Then use that knowledge and apply it to your
problem.
When the program starts, Smallest is assigned the value 3, since
Numbers[0] equals 3. Then the loop starts, i gets a value of 1.
The if tests if Numbers[i], that is Numbers[1], which has the
value 8, is less then Smallest, which has the value 3.
Well. 8 is not less then 3, thus nothing happens. There is
nothing more in the loop body, thus i is incremented, and since
i is less then 5, the loop body is executed again.
The if tests if Numbers[2], value: 2, is less then Smallest (value: 3)
Yes. 2 is less then 3, thus the if body is taken, which assigns
the value of Numbers[2], which happens to be 2, to Smallest, thus
Smallest equals 2 now.
The loop makes one more turn and compares Numbers[3], (value: 5)
with Smallest (value: 2). 5 is not less then 2, thus nothing happens
in the loop.
Next turn through the loop: Compare Numbers[4] (value 6) with
Smallest (value: 2). 6 is not less then 2, thus nothing happens
in the loop body.
The loop is then terminated since i has reached the value 5, which
terminates the loop .... and ....
Smallest contains the smallest value found in the array: 2
HTH
--
Karl Heinz Buchegger
kb******@gascad.at