07/03/2016

Java Program to Reverse a Number Using While Loop

Problem:- Java Program to Reverse a Number, write a Java Program to Reverse a Number Using While Loop Ie. If a number is 12345 then it prints 54321.

Logic:- Logic for reverse a digit is simple lets take an example 12345 now first we divide a number with 10 so we get reminder 5 store the reminder and then and using this logic we multiply rev = rev * 10 + rem and again divide the number with 10 ,now number is 1234 and repeat a process again and again until number becomes greater or equal 1.Or you can try this problem with different -2 loop


Note:- Always remember Do Not try to print the reverse Digit always try to modify Like you can also solve the problem

while(n!=0)
{
rev=n%10;
System.out.print("Reversed Number = "+reverse);
n=n/10
}
but in this way number is printing actually not reversing. If you Understood then try to solve given a problem.


Extreme Recommended:- Like our Facebook Page or Join our Facebook Group and Google plus Community for up-to-date for a new post or if you have any Query you can ask there with lots of coders also suggest to your Friends to join and like our page, so we can help our community, and don't forget to Subscribe. Enter your Email and click to subscribe.

Try Yourself- C Program to Check a Number is Palindrome or Not Using While Loop



Java Program to Reverse a Number Using While Loop



/*Program By Ghanendra Yadav
   Visit http://www.programmingwithbasics.com/
*/

import java.util.Scanner;

public class reverse
{
    public static void main(String args[])
    {
        int n, reverse=0, rem;
 Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter The Number That You Want Reverse : \n\n");
        n = sc.nextInt();
 
 while(n!=0)
 {
 rem=n%10;
 reverse=reverse*10+rem;
 n/=10;
 }
 
 System.out.print("Reversed Number = "+reverse);
 
 }
}

Output:-

Java Program to Reverse a Number Using While Loop
Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: