Reputation: 21
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
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
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