[Solved] Can’t seem to get the right value in a for loop with and if-else statement [closed]


Other responders have given you a better way to write this, but to specifically address your original question, the reason you’re getting an “unexpected” (to you) value of “low” is that you’re assigning each entry of the array to “low” unconditionally. The entry with “5” is the last entry that you process, so that’s the value you end up with.

To address this specific problem, you might assign the array entry value to a new local variable, called “newlow”, perhaps. Then, compare “newlow” to the existing “low” value and then conditionally assign it, perhaps like this:

            low = numArray[0];
            for (int countB = 0; countB < numArray.length-1; countB++) {
                int newlow = numArray[countB];
                if (newlow < low) {
                    low = newlow;
                }
            }   

1

solved Can’t seem to get the right value in a for loop with and if-else statement [closed]