158k views
4 votes
Consider the following code segment.

for (int k = 0; k < 4; k++)
{
/* missing loop header */
{
System.out.print(k);
}
System.out.println();
}
The code segment is intended to produce the following output.
0
11
222
3333

Which of the following can be used to replace /* missing loop header */ so that the code segment will work as intended?

a. for (int h = 0; h < k; h++)
b. for (int h = 1; h < k + 1; h++)
c. for (int h = 0; h < 3; h++)
d. for (int h = k; h >= 0; h--)
e. for (int h = k; h <= 0; h--)

User Theressa
by
7.5k points

1 Answer

3 votes

Answer:

for (int h = k; h >= 0; h--)

Step-by-step explanation:

From the list of given options, option C answers the question.

In the outer loop

Initially, k = 0

In the inner loop,

h = k = 0

The value of h will be printed once because h>=0 means 0>=0 and this implies once

To the outer loop

k = 1

The inner loop will always assume value of k;

So,

h = 1

This will be printed twice because of the condition h>=0 means 1>=0.

Since 1 and 0 are >=0; 1 will be printed twice

To the outer loop

k = 2

The inner loop

h = 2

This will be printed thrice because of the condition h>=0 means 2>=0.

Since 2, 1 and 0 are >=0; 2 will be printed thrice

To the outer loop

k = 3

The inner loop

h = 3

This will be printed four times because of the condition h>=0 means 3>=0.

Since 3, 2, 1 and 0 are >=0; 3 will be printed four times

User Elicohenator
by
7.9k points