Print Numbers N to 1 in Java
Problem
A for loop can count downward just as easily as upward, by starting at the high end and decrementing instead of incrementing.
Given a number n, print every integer from n down to 1.
Java Program
public class PrintNumbersNToOne {
public static void main(String[] args) {
int n = 10;
for (int i = n; i >= 1; i--) {
System.out.println(i);
}
}
}Output
Core Logic
Starting the counter at n and decrementing it each step, instead of incrementing from 1, produces the sequence in reverse order.
- 1
for (int i = n; i >= 1; i--)starts the counter atnand stops once it drops below 1. - 2Each iteration prints the current value of
ibefore decreasing it. - 3Flipping the starting point, the comparison direction, and the step direction together is what reverses the whole sequence.
n = 10, the loop runs ten times, printing 10 down to 1 in order.Key Point: All three parts of the loop header have to flip together — starting high, comparing with >=, and stepping with i-- — changing only one of them would break the countdown.
Why: The loop runs exactly n times printing one number each, with no growing storage, the same cost as counting upward.
Key Concepts
Approach 2: Java 8
import java.util.Comparator;
import java.util.stream.IntStream;
public class PrintNumbersNToOneStream {
public static void main(String[] args) {
int n = 10;
// No descending rangeClosed() exists, so box and sort in reverse
IntStream.rangeClosed(1, n)
.boxed()
.sorted(Comparator.reverseOrder())
.forEach(System.out::println);
}
}
Output
Core Logic
IntStream has no built-in descending range, so the ascending stream is boxed and explicitly sorted in reverse to get the same countdown.
- 1
IntStream.rangeClosed(1, n)produces every integer from 1 ton, in ascending order — there's norangeClosed()variant that counts down directly. - 2
.boxed()converts the primitiveintstream into aStream<Integer>, sincesorted()with a custom comparator needs an object stream. - 3
.sorted(Comparator.reverseOrder())flips the ascending sequence into descending order. - 4
.forEach(System.out::println)prints each value in that reversed order.
n = 10, boxing and reverse-sorting 1..10 produces the same 10-down-to-1 sequence the loop prints.Key Point: Unlike the plain 1-to-n stream, this one needs an explicit sort step — IntStream simply has no descending counterpart to rangeClosed(), so boxing plus Comparator.reverseOrder() is the standard workaround.
Why: Boxing and sorting n values costs O(n log n) and needs an internal buffer of size n, unlike the loop's O(n) time and O(1) space.