Write a program to print all natural numbers in reverse


This Java program is similar to the previous one, except that it prints the natural numbers in reverse order. It prompts the user to input two integers, a starting number and an ending number, and then uses a while loop to print all the natural numbers from the starting number to the ending number in reverse order.

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 Reverse_Numbers 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 greater 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 decremented 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 greater 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 Reverse_Numbers
{
	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 : 10
Enter The Ending Number : 1
10
9
8
7
6
5
4
3
2
1

Example Programs