0
0
JavaProgramBeginner · 2 min read

Java Program to Print Numbers 1 to n

You can print numbers from 1 to n in Java using a for loop like this: for (int i = 1; i <= n; i++) { System.out.println(i); }.
📋

Examples

Input1
Output1
Input5
Output1 2 3 4 5
Input0
Output
🧠

How to Think About It

To print numbers from 1 to n, start at 1 and keep increasing the number by 1 until you reach n. For each number, print it on the screen. This is like counting out loud from 1 up to n.
📐

Algorithm

1
Get the input number n.
2
Start a counter at 1.
3
While the counter is less than or equal to n, do the following:
4
Print the current counter value.
5
Increase the counter by 1.
6
Stop when the counter exceeds n.
💻

Code

java
import java.util.Scanner;

public class PrintNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            System.out.println(i);
        }
        scanner.close();
    }
}
Output
1 2 3 4 5
🔍

Dry Run

Let's trace the program with input n = 5 through the code

1

Read input

User inputs n = 5

2

Initialize loop

Set i = 1

3

Check condition

Is i (1) <= n (5)? Yes, continue

4

Print number

Print 1

5

Increment counter

i becomes 2

6

Repeat loop

Check i <= 5, print i, increment i until i = 6

7

End loop

When i = 6, condition fails, stop

iCondition i <= nAction
1truePrint 1
2truePrint 2
3truePrint 3
4truePrint 4
5truePrint 5
6falseStop loop
💡

Why This Works

Step 1: Input reading

The program reads the number n from the user using Scanner.

Step 2: Loop setup

A for loop starts from 1 and runs until it reaches n, inclusive.

Step 3: Printing numbers

Inside the loop, each number i is printed on its own line using System.out.println(i).

🔄

Alternative Approaches

while loop
java
import java.util.Scanner;

public class PrintNumbersWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int i = 1;
        while (i <= n) {
            System.out.println(i);
            i++;
        }
        scanner.close();
    }
}
Uses a while loop instead of for loop; functionally the same but some find while loops clearer for this task.
do-while loop
java
import java.util.Scanner;

public class PrintNumbersDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int i = 1;
        if (n >= 1) {
            do {
                System.out.println(i);
                i++;
            } while (i <= n);
        }
        scanner.close();
    }
}
Uses a do-while loop which runs the loop body at least once; requires a check to handle n < 1.
recursion
java
import java.util.Scanner;

public class PrintNumbersRecursion {
    public static void printNumbers(int i, int n) {
        if (i > n) return;
        System.out.println(i);
        printNumbers(i + 1, n);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        printNumbers(1, n);
        scanner.close();
    }
}
Uses recursion to print numbers; elegant but less efficient and can cause stack overflow for large n.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs from 1 to n, so it executes n times, making the time complexity O(n).

Space Complexity

The program uses a fixed amount of extra space regardless of n, so space complexity is O(1).

Which Approach is Fastest?

All loop-based approaches have similar O(n) time and O(1) space. Recursion uses more stack space and is slower for large n.

ApproachTimeSpaceBest For
For loopO(n)O(1)Simple and clear iteration
While loopO(n)O(1)Similar to for loop, preferred by some for clarity
Do-while loopO(n)O(1)Runs loop body at least once, needs extra check for n < 1
RecursionO(n)O(n)Elegant but uses more memory, risky for large n
💡
Always close your Scanner object after use to avoid resource leaks.
⚠️
Forgetting to include the equal sign in the loop condition, causing the last number n not to print.