NoxiousL
NoxiousL

Reputation: 3

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 }

Upvotes: 0

Views: 1313

Answers (3)

Sridutt Saripella
Sridutt Saripella

Reputation: 1

The final value of result should return 22. This is because the the loop runs from i < 4, which means it does not include the 4th index position in the loop. The final loop ends at the 3rd index position and since data[i] is not greater than result. the 3rd index is 22 and result is 1000 and since 22 is not greater than 1000, the program returns 22.

Upvotes: 0

Sundaram
Sundaram

Reputation: 31

After the test, what do you think below line of code do?

result = data[i];

Upvotes: 1

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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)

Upvotes: 0

Related Questions