Search code examples
javaarraystrace

Java Code Tracing of Arrays


I'm having trouble with this school work, you have to trace the code of this array using a tracing table, however I am stuck for an answer.

When I go through the code I get to the line where data[i] is given the index position of 0, which is 50. I then get confused as to if the table stops on that line because it cannot proceed because of data[i] is not less than data.length. So does it end there or am I wrong?

public static int ???(int[] data) {

    int result = 1000;

    for (int i = 0; i < data.length; i++) {
        if (data[i] < result) {
            result = data[i];
        }
    }

    return result;
}

and the data is

{ 50, 43, 22, 30 }


Solution

  • for (int i = 0; i < data.length; i++)

    You compare i with data.length, not data[i] with data.length so your loop run as expected (ie does not end at i = 0)