132k views
2 votes
What is the output of the following Java code?int x = 1;do{System.out.print(x + " ");x--;}while (x > 0);System.out.println();

User Pdel
by
5.9k points

1 Answer

5 votes

Answer:

The output is 1.

Step-by-step explanation:

int x = 1;

do{

System.out.print(x + " ");

x--;

}while (x > 0);

System.out.println();

The statement above is an example of a do-while loop which is always executed at least once.

In the above code snippet:

1 is assigned to x in the first line. Then the do keyword start the loop block. Inside the loop block, the value of x is output which is one (1). Then, the value of x is decreased by one, making x = 0. Then, the while keyword is reached where the condition is tested. The condition check whether x > 0 i.e whether 0 > 0. Off course, the condition is false and the loop is exited.

The last statement print a single line to the screen.

User Skimrande
by
5.9k points