AbHi TheNua
AbHi TheNua

Reputation: 21

How to print the counting in reverse order from 10 to 1 in java?

I want to print reverse order of counting. How can I do that in java? I tried a little bit code but not succeed.

import java.util.*;
public class reversecount 
{
    public static void main(String [] args)
    {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Any Number");
        num = sc.nextInt();

        for(num=1; num<=10; num--)
        {
            System.out.println(num);
        }
    }
}

Upvotes: 1

Views: 10349

Answers (2)

kunwar97
kunwar97

Reputation: 825

You are making an infinite loop because num will always be smaller than 10. The value of num is decreasing with the passes of loop.

for (num = 10; num >= 0; num--) { 
    System.out.println(num);
} 

This will print the array in reverse order like 10,9,8,7,6,5,4,3,2,1,0

According to the comment. Use while loop

while(num>=0){
      System.out.println(num);
      num--;
}

This will do the work for you.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311188

You need to start at 10 (not 1), and continue as long as the value is larger than 0:

for (num = 10; num > 0; num--) {
    System.out.println(num);
}

Upvotes: 1

Related Questions