35.1k views
8 votes
Fix the infinite loop so that it counts from 3 down to 1.public class Loop1{public static void main(String[] args){int x = 3;while (x > 0){System.out.println(x);}}}

1 Answer

10 votes

Answer:

Include x-- right after the print statement

Step-by-step explanation:

Given:

The above lines of code

Required

Edit to countdown from 3 to 1

The above code (as it is) prints 3 in infinite times. To make it countdown to 1, we simply include a decrement operation.

Initially, the value of x is 3: int x = 3;

And the condition is that the loop is to be repeated as long as x > 0

All we need to do is to include x-- right after the print statement.

This operation will reduce the value of x on every iteration as long as the condition is true.

Hence, the complete code is:

public class Loop1{

public static void main(String[] args){

int x = 3;

while (x > 0){

System.out.println(x);

x--;

}}}

User Gates
by
3.7k points