Write a program to print all natural numbers from 1 to n


This Java program prompts the user to input two integers, a starting number and an ending number. It then uses a while loop to print all the natural numbers from the starting number to the ending number, inclusive.

Here's a step-by-step breakdown of how the program works:

  • The program starts by importing the java.util.Scanner class, which is used to read user input from the console.
  • The Natural_Number class is defined and the main method is declared.
  • Inside the main method, an instance of the Scanner class is created and assigned to a variable named input.
  • The program prompts the user to input the starting number by printing the message "Enter The Starting Number : " to the console. The nextInt() method of the Scanner class is then used to read an integer value from the console and assign it to a variable named s.
  • The program prompts the user to input the ending number by printing the message "Enter The Ending Number : " to the console. The nextInt() method of the Scanner class is then used to read an integer value from the console and assign it to a variable named e.
  • The program enters a while loop that will execute as long as the value of s is less than or equal to the value of e.
  • Inside the while loop, the program prints the value of s to the console using the println() method of the System.out object.
  • The value of s is then incremented by 1 using the ++ operator.
  • The program returns to the beginning of the while loop and checks the condition again. If the value of s is still less than or equal to the value of e, the loop will continue to execute. If not, the loop will terminate and the program will exit.

Source Code

import java.util.Scanner;
class Natural_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Starting Number : ");
		int s =input.nextInt();
		System.out.print("Enter The Ending Number : ");
		int e =input.nextInt(); 
		while(s<=e)
		{
			System.out.println(s);
			s++;
		}
	}
}

Output

Enter The Starting Number : 1
Enter The Ending Number : 10
1
2
3
4
5
6
7
8
9
10

Example Programs