๐ Introduction
Natural numbers are the numbers used for counting — starting from 1, 2, 3, 4, 5, ... and so on.
In this Java program, we’ll learn how to print the first N natural numbers, where N is provided by the user.
This is one of the simplest programs to start learning loops and input handling in Java.
⚙️ Logic Behind the Program
-
Accept the number N from the user.
-
Use a for loop to print numbers from 1 to N.
-
Each number is printed in the same line (or separately depending on your choice).
๐ป Java Code
// Java program to print first N natural numbers
import java.util.Scanner;
public class NaturalNumbers {
public static void main(String[] args) {
// Create Scanner object to take input from user
Scanner sc = new Scanner(System.in);
// Asking the user to enter a number
System.out.print("Enter the value of N: ");
int n = sc.nextInt();
// Display message
System.out.println("The first " + n + " natural numbers are:");
// Loop from 1 to n
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
// Close scanner
sc.close();
}
}
๐ง Explanation of the Code
| Line | Explanation |
|---|---|
import java.util.Scanner; |
Imports the Scanner class for user input. |
Scanner sc = new Scanner(System.in); |
Creates a Scanner object to read input. |
int n = sc.nextInt(); |
Takes the number (N) from the user. |
for (int i = 1; i <= n; i++) |
Loop starts from 1 and runs until it reaches N. |
System.out.print(i + " "); |
Prints numbers in the same line separated by spaces. |
๐งพ Example Output
Input:
Enter the value of N: 5
Output:
The first 5 natural numbers are:
1 2 3 4 5
๐ก Alternative: Using While Loop
You can also use a while loop to achieve the same result:
import java.util.Scanner;
public class NaturalNumbersWhile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int n = sc.nextInt();
int i = 1;
while (i <= n) {
System.out.print(i + " ");
i++;
}
sc.close();
}
}
๐ Conclusion
This program is a great starting point to understand:
-
Loops (for and while)
-
User input using Scanner
-
Basic logic building in Java
Comments
Post a Comment