K G
K G

Reputation: 17

Computer Science: Java MC

private int[] myStuff;
/** Precondition: myStuff contains int values in no particular order.
  /*/ 
public int mystery(int num)
{
    for (int k = myStuff.length-1; k>=0; k--)
    {
        if (myStuff[k] < num)
        {
           return k;
        }
    }
return -1;
}

Which of the following best describes the contents of myStuff after the following statement has been executed?

int m = mystery(n); 

Answer: All values in positions m+1 through myStuff.length-1 are greater than or equal to n.

Can anyone explain why this answer is correct? I'm not sure what they mean by contents but, I concluded that myStuff is unchanged because the code doesn't alter the value of myStuff.

Upvotes: 0

Views: 413

Answers (3)

PM 77-1
PM 77-1

Reputation: 13334

The question about the content is valid. It has nothing to with whether the content itself was changed.

This method returns either a non-negative number when there is such k (from myStuff.length-1 to 0) that myStuff[k] is less than n, or -1 when all elements of myStuff are more than or equal to n.

Let's consider both cases:

  • m is non-negative number - it means that position m was the last from the right that satisfied the condition myStaff[m] < n, your answer is correct

  • m is -1 - it means that all elements are more than equal than m+1 (which in this case is 0) - hence the answer is correct

Upvotes: 0

Colin D
Colin D

Reputation: 5661

You are correct that myStuff is unchanged. However, they are asking about the relationship between the data in the array, the return value of the function, and the function's arguments.

The code does the following:

  • Iterates the array in reverse order. (for loop)
  • At each index during the iteration, it checks the value of that index against n, returning the current index if n is larger. (if statement)

So what does the method return? It returns the first index from the end where mystuff[m] < n. (mystuff[i] >= num)

Upvotes: 1

AcId
AcId

Reputation: 458

Precondition says, that myStuff contains integer values in no particular order. The for loop is initialized with k equal to the lenght of myStuff minus one (since array indices start at zero), iterates while k is greater than or equal to zero and subtract one from k in each iteration.

If you look at the if statement, it will return the current value of k, when the value at the corresponding index of myStuff[k] is less than n; hence all values in array indices greater than the returned value plus one, must be greater than or equal to n. And if no numbers integers in myStuff are greater than n, minus one is returned.

I hope this helps.

Btw - you're right that the content of mySyuff isn't changed.

Upvotes: 1

Related Questions