144k views
1 vote
Assume the following method has been defined:

public static int mystery(String a[], int x) {
int c = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].length() > x)
c++;
}
return c;
}

What is output by the following code?

String b [] = {"aardvark", "banana", "cougar", "daikon", "elephant", "fog", "get"};
System.out.println(mystery(b, 5));

User Syed Tariq
by
6.0k points

1 Answer

3 votes

Answer:

The output is 5

Step-by-step explanation:

In the code snippet given in the question, we have a variable C which is initially set to zero and it is incremented by 1 after every iteration of the loop.

Within the for loop statement we have a condition that compares the length of the ith element of the array with a variable x (both the array and x) passed as an argument to the method mystery.

When mystery is called, it is given an array of strings with 7 elements, and x=5 as arguments. So at the first iteration, C=0, and length of ith element = 0, C is incremented by 1 and the loop goes on again to C = 1, 2, 3, 4, 5 at C = 5, the ith element is greater that x which is 5. so the loop breaks and C is returned and printed out.

User Sheshadri
by
5.9k points