Java Program to Print Numbers from 1 to n

In this tutorial, you will learn how to write a Java program that prints numbers from 1 to n by taking the value of n as input from the user.

In Java, we can handle repetitive tasks like this using different looping statements such as for, while, and do-while.

A loop allows you to execute a block of code repeatedly until a specified condition evaluates to false. So, let’s start with the for loop.

Java Program to Print Numbers from 1 to n Using for Loop

The for loop is the simplest and most commonly used approach to print numbers from 1 to n in Java.

In this approach, we initialize a loop variable i with 1 and execute the loop as long as i is less than or equal to n. After printing each number, we increment the value of i by 1.

So, let’s write a Java program to print numbers from 1 to n using the for loop.

Java Program

import java.util.Scanner;
public class PrintNumbers {
    public static void main(String[] args) {
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the value of n
        System.out.print("Enter the value of n: ");
        int n = scanner.nextInt();

        // Validate that the input is a positive integer (greater than or equal to 1)
        if (n >= 1) {
            System.out.println("Numbers from 1 to " + n + " are:");

            // Loop from 1 to n and print each number on a new line
            for (int i = 1; i <= n; i++) {
                System.out.print(i+ " ");
            }
        } else {
            // Handle invalid input where n is less than 1
            System.out.println("Please enter a positive integer greater than or equal to 1.");
        }

        // Close the scanner resource to prevent memory leaks
        scanner.close();
    }
}

Output:

Enter the value of n: 10
Numbers from 1 to 10 are:
1 2 3 4 5 6 7 8 9 10

Explanation of the Java Program

Let’s understand how this Java program works step by step.

  1. Import the Scanner class: First, we import the Scanner class from the java.util package to accept an input number from the keyboard.
  2. Create a Scanner object: We create an object named scanner of the Scanner class to read the user’s input.
  3. Read the value of n: The nextInt() method reads an integer number entered by the user and stores it in the variable n.
  4. Check the input: We use an if statement to check whether the entered number is greater than or equal to 1. If the number is less than 1, the program displays an appropriate message.
  5. Initialize the loop variable: Inside the for loop, we initialize the variable i with 1.
  6. Check the condition: The condition i <= n checks whether the current value of i is less than or equal to n. If the condition is true, the loop body executes.
  7. Print the number: The System.out.print(i+ " ") statement prints the current value of i on the console.
  8. Increment the variable: The increment operator i++ increases the value of i by 1 after every iteration.
  9. Terminate the loop: When the value of i becomes greater than n, the condition becomes false, and the loop terminates.

Thus, the above Java program prints all numbers starting from 1 up to the user-entered value of n on the console.

Java Program to Print Numbers from 1 to n Using while Loop

We can also print numbers from 1 to n using a while loop in Java. A while loop repeatedly executes a block of statements as long as its specified condition remains true.

In this approach, we initialize a control variable i to 1 before the loop starts. The loop checks the condition i <= n before each iteration; if true, it prints the value of i and increments i by 1 (i++) to eventually terminate the loop.

Let’s look at the complete Java program to print numbers from 1 to n using a while loop.

Java Program

import java.util.Scanner;
public class PrintNumbersWhileLoop {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the value of n
        System.out.print("Enter the value of n: ");
        int n = scanner.nextInt();

        // Validate that n is positive
        if (n >= 1) {
            System.out.println("Numbers from 1 to " + n + " are:");

            // Initialize the loop variable before the loop
            int i = 1;

            // Condition check
            while (i <= n) {
                // Print the current value of i
                System.out.print(i+ " ");

                // Increment the variable (crucial to prevent infinite loops)
                i++;
            }
        } else {
            System.out.println("Please enter a positive integer greater than or equal to 1.");
        }

        // Close the scanner
        scanner.close();
    }
}

Output:

Enter the value of n: 15
Numbers from 1 to 15 are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Explanation of the Java Program

Let’s understand how this Java program works step by step.

  1. Import the Scanner class: First, we import the Scanner class from the java.util package to accept input from the keyboard.
  2. Create a Scanner object: We create an object named scanner of the Scanner class to read the user’s input.
  3. Read the value of n: The nextInt() method reads an integer entered by the user and stores it in the variable n.
  4. Check the input: We use an if statement to check whether the entered number is greater than or equal to 1. If the number is less than 1, the program displays an appropriate message.
  5. Initialize the loop variable: Unlike a for loop, we initialize the control variable i with 1 before the while loop begins (int i = 1;).
  6. Check the condition: The while condition i <= n checks whether the current value of i is less than or equal to n. If the condition evaluates to true, the loop body executes.
  7. Print the number: The System.out.print(i+ " ") statement prints the current value of i on the console.
  8. Increment the variable: The i++ operator increases the value of i by 1 after each iteration.
  9. Terminate the loop: When i becomes greater than n, the condition becomes false, and the while loop terminates.

Thus, the program successfully prints all numbers starting from 1 up to the user-entered value of n using a while loop.

Java Program to Print Numbers from 1 to n Using do-while Loop

The do-while loop is another way to print numbers from 1 to n in Java. Unlike the for and while loops, the do-while loop checks its condition after executing the loop body. Therefore, it executes at least once. Let’s look at the complete Java program using do-while loop.

Java Program

import java.util.Scanner;
public class PrintNumbersDoWhileLoop {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the value of n
        System.out.print("Enter the value of n: ");
        int n = scanner.nextInt();

        // Validate that n is positive
        if (n >= 1) {
            System.out.println("Numbers from 1 to " + n + " are:");

            // Initialize the loop variable before the loop
            int i = 1;

            // Do-while loop implementation
            do {
                // Print the current value of i
                System.out.print(i+ " ");

                // Increment the variable
                i++;

            } while (i <= n); // Condition checked after execution
            
        } else {
            System.out.println("Please enter a positive integer greater than or equal to 1.");
        }
        // Close the scanner
        scanner.close();
    }
}

Output:

Enter the value of n: 7
Numbers from 1 to 7 are:
1 2 3 4 5 6 7

In this example program, the code inside the do block runs immediately without checking any condition—printing the number and incrementing i (i++).

After executing the body once, the while (i <= n) condition is evaluated. If the condition is true, the loop jumps back to the do block for the next iteration. If it becomes false, the loop terminates.

Print Numbers from 1 to n in Multiple Lines

In the previous examples, we printed each number on a single line separated by spaces using System.out.print(). If you want to print all numbers in multiple lines, you can use the System.out.println() method instead.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.