How to count backwards (Print the numbers N, N - 1, ..., 0 (included)) in Java

4 Answers

0 votes
public class Program {
    public static void main(String[] args) {
        int n = 5;
        
        for (int i = n; i != -1; i--) {
            System.out.print(i + " ");
        }
    }
}
 
 
/*
run:
   
5 4 3 2 1 0
      
*/

 



answered Jul 20, 2025 by avibootz
edited Jul 20, 2025 by avibootz
0 votes
import static java.lang.System.out;
 
public class Program {
    public static void main(String[] args) {
        int n = 5;
        
        for (int i = n; i != -1; out.print(i-- + " "));
    }
}
 
 
/*
run:
   
5 4 3 2 1 0 
      
*/

 



answered Jul 20, 2025 by avibootz
edited Jul 20, 2025 by avibootz
0 votes
import static java.lang.System.out;
import static java.util.stream.IntStream.iterate;
 
public class Program {
    public static void main(String[] args) {
        int n = 5;
         
        iterate(n, x -> x - 1)
            .limit(n + 1)
            .forEach(out::println);   
    }
}
 
 
/*
run:
   
5
4
3
2
1
0
      
*/

 



answered Jul 20, 2025 by avibootz
edited Jul 20, 2025 by avibootz
0 votes
import static java.lang.System.out;
import static java.util.stream.IntStream.iterate;
 
public class Program {
    public static void main(String[] args) {
        int n = 5;
         
        iterate(n, x -> x - 1)
            .limit(n + 1)
            .forEach(x -> out.print(x + " "));   
    }
}
 
 
/*
run:
   
5 4 3 2 1 0 
      
*/
 

 



answered Jul 20, 2025 by avibootz
edited Jul 20, 2025 by avibootz
...