54.8k views
4 votes
Consider the following code segment.

int j = 1;
while (j <= 5)
{
for (int k = 4; k > 1; k--)
{
System.out.println("ha"); // line 6
}
j++;
}
How many times will the print statement on line 6 execute?
A. 15
B. 16
C. 20
D. 24
E. 25

1 Answer

5 votes

Final answer:

The print statement executes 15 times, as the inner for loop runs 3 times for each iteration of the outer while loop, which runs 5 times in total.

Step-by-step explanation:

The given code is a nested loop. The outer while loop will execute 5 times because it starts at 1 and continues until j exceeds 5. Each time the while loop executes, the inner for loop starts at 4 and decrements the value of k until it is greater than 1.

The for loop runs for k = 4, 3, 2, which is 3 iterations. Since the outer while loop runs 5 times, the total number of times the println statement is executed is:

5 (outer loop runs) * 3 (inner loop runs) = 15.

So, the correct answer is A. 15 times.

Related questions