Monday, 7 March 2016

Java Program to Reverse a Number Using While Loop

Problem :- Write a Java Program to Reverse a Number Using While Loop Like Number is 12345 then it print 54321

Logic :- Logic for reverse a digit is simple lets take a 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 become greater or equal 1.Or you can try this problems with different -2 loop

Note :- Always remember Do Not try to print the reverse Digit always try to modified 
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 problem .

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

Solution :-

/*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

No comments:
Write comments

Recommended Posts × +