Java ProgramsControl FlowPrint Numbers 1 to N

Print Numbers 1 to N in Java

beginner·  Control Flow  ·  Loops

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.

Input
n = 10
Output
1 2 3 4 5 6 7 8 9 10

Java Program

Java
public class PrintNumbersOneToN { public static void main(String[] args) { int n = 10; for (int i = 1; i <= n; i++) { System.out.println(i); } } }

Output

1 2 3 4 5 6 7 8 9 10

Core Logic

Counting a variable upward from 1 to n, and printing it at every step, produces the full sequence in order.

How It Works
  1. 1for (int i = 1; i <= n; i++) starts the counter at 1 and stops once it passes n.
  2. 2Each iteration prints the current value of i before advancing.
  3. 3The loop's own counter is the entire sequence — no separate array or list is built to hold it.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The loop runs exactly n times printing one number each, with no growing storage.

Key Concepts

for looploop counterSystem.out.println()

Approach 2: Java 8

Java
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

1 2 3 4 5 6 7 8 9 10

Core Logic

The same 1-to-n sweep can be generated directly as a stream, without managing a loop counter by hand.

How It Works
  1. 1IntStream.rangeClosed(1, n) produces every integer from 1 to n, inclusive.
  2. 2.forEach(System.out::println) prints each value in order, using a method reference instead of a lambda body.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The stream still visits each of the n values exactly once and prints it directly, without collecting anything.

Key Concepts

StreamIntStream.rangeClosed()forEach()

Related Programs