Program to reverse a number (Java)

So today we are going to write program that accepts a number from the user and print the reversed number. So this is a very simple program and it does not require much logic to write this program.
So lets get started...


Q. Write a program that accepts an integer from the user and print the reversed number.
For Example: Input: 12345 , and Output: 54321

Solution:
123456789101112131415161718 import java.util.*;
 class ReverseNumber
 {
     public static void main(String[] args)
     {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a number: ");
         int n = sc.nextInt();
         int reminder,reverse = 0;
         for(int i = n;i > 0;i=i/10)
         {
             reminder = i%10;
             reverse = reverse*10+reminder;
         }
         System.out.println("Reverse of " + n + " = " + reverse);
     }
 }

Code Written in BlueJ

Output:
1234Enter a number: 
12345
Reverse of 12345 = 54321

Output in BlueJ

Variable description used in program:
int n - It is used to accept an integer from the user.
int reminder - It is used to take the last digit of the number when divided by 10 i.e., n%10 = Its reminder (Last digit).
int reverse - It is used to reverse the given number.
Explanation:
In this program first we accepted an integer i.e., "int n" from the user using Scanner class. Then we created two variable i.e., "int reminder" and "int reverse" for their respective work. Further we made for() loop for reversing the number. In for() loop the initialisation, condition and update statements are given according to their working. And inside for() loop "int reminder" is used to take the last digit of the number and "int reverse" is used to reverse and store the reversed digit. If you know the working of for() loop then you will be able to understand this easily, and also make flowchart while understanding the programs.

So that is it to print the Reversing a Number program. Hope you find it useful and if you have any query do comment in the comment box and I will try to solve your query. Will see you on next program.

Thank You.
Program to reverse a number (Java) Program to reverse a number (Java) Reviewed by Get2Know on September 22, 2020 Rating: 5

No comments:

Powered by Blogger.