Print Numbers 1 to N in Java
Problem
A for loop can walk through a fixed range one step at a time, printing each value as it goes — the simplest possible use of a counter-controlled loop.
Given a number n, print every integer from 1 to n.
Java Program
public class PrintNumbersOneToN {
public static void main(String[] args) {
int n = 10;
for (int i = 1; i <= n; i++) {
System.out.println(i);
}
}
}Output
Core Logic
Counting a variable upward from 1 to n, and printing it at every step, produces the full sequence in order.
- 1
for (int i = 1; i <= n; i++)starts the counter at 1 and stops once it passesn. - 2Each iteration prints the current value of
ibefore advancing. - 3The loop's own counter is the entire sequence — no separate array or list is built to hold it.
n = 10, the loop runs ten times, printing 1 through 10 in order.Key Point: The loop condition i <= n, not i < n, is what includes n itself in the printed sequence.
Why: The loop runs exactly n times printing one number each, with no growing storage.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PrintNumbersOneToNStream {
public static void main(String[] args) {
int n = 10;
IntStream.rangeClosed(1, n).forEach(System.out::println);
}
}
Output
Core Logic
The same 1-to-n sweep can be generated directly as a stream, without managing a loop counter by hand.
- 1
IntStream.rangeClosed(1, n)produces every integer from 1 ton, inclusive. - 2
.forEach(System.out::println)prints each value in order, using a method reference instead of a lambda body.
n = 10, the stream produces the same ten values the loop does, printed in the same order.Key Point: rangeClosed() already includes the upper bound, matching the loop version's i <= n — the plain range() method would stop one short.
Why: The stream still visits each of the n values exactly once and prints it directly, without collecting anything.