Print all natural numbers in reverse order While loop Java

Print all natural numbers in reverse order While loop Java

Positive whole numbers are called Natural numbers. In this program, we are trying to print all the natural numbers in reverse using a while loop starting from n to 1. n being the starting point decided at runtime which will be given by user.

For example:

Suppose the given input is 5,

Then output will be 5, 4, 3, 2, 1

Steps for reverse program

  • Here we are using “Scanner” to take input for number.
  • we are running the while loop in reverse and decrementing the number by one
eg. number=9
since 9>=1. it goes into while loop
inside the loop it prints the number and then decrements it by 1, now number is 9-2=8
this continues till the loop coondition is met.

Java Program to print All natural number in reverse order

import java.util.*;
public class Main
{
	public static void main(String args[])
	{
	    System.out.println("Print all natural numbers in reverse order ");
		Scanner sc = new Scanner(System.in);
		System.out.println("Give Input to print reverse natural numbers : ");
		int number = sc.nextInt();
		while(number >=1) {
			System.out.print(number +",");
			number--;
		}
		sc.close();
	}
}

Output 1:

Print all natural numbers in reverse order 
Give Input to print reverse natural numbers : 
5
5,4,3,2,1,

Output 2:

Print all natural numbers in reverse order 
Give Input to print reverse natural numbers : 
8
8,7,6,5,4,3,2,1,