Java program to reverse a number

Java program to reverse a number:

In this page, you'll learn how to reverse a number using while loop, for loop, array, recursive method.

java,reverse a number,java program to reverse a number,how to reverse number in java,how to reverse a number in java,reverse number in java,java program,reverse a number in java,reverse a number java code,program,java tutorial for beginners,reverse number,how to reverse number,program to reverse a number,write a program to reverse this number,java program to reverse a string,number


Example 1:
Using the while loop

import java.util.Scanner;
class Reverse_number
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = sc.nextInt();
int reverse = 0;
while(num!=0)
{
reverse = (reverse*10) + (num%10);
num = num/10;
}
System.out.println("After reversing the number: " + reverse);
}
}

Output:
Enter the number: 678
After reversing the number: 876

Example 2:
Using the for loop

import java.util.Scanner;
public class Example2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = sc.nextInt();
int reverse = 0;
for(; num!=0; num/=10)
{
reverse = (reverse*10) + (num%10);
}
System.out.println("After reversing the number: " + reverse);
}
}

Output:
Enter the number: 8975
After reversing the number: 5798

Example 3:
Using the array

import java.util.Scanner;
public class Example3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = sc.nextInt();
int copy_num = num,count = 0;
while(copy_num!=0)
{
copy_num = copy_num/10;
count++;
}
int[] reverse = new int[count];
for(int i=0; i<=(count-1); i++)
{
if(num!=0)
{
reverse[i] = num%10;
num = num/10;
}
}
System.out.print("After reversing the number: ");
for(int r:reverse)
{
System.out.print(r);
}
}
}


Output:
Enter the number: 5436254
After reversing the number: 4526345

Example 4:
Using the recursive method

Note: Method that call itself is known as recursive method

import java.util.Scanner;
public class Example4
{
public static void reverse(int reverse_number)
{
if(reverse_number!=0)
{
System.out.print(reverse_number%10);
reverse(reverse_number/10);
}
else
{
return;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = sc.nextInt();
System.out.print("After reversing the number: ");
reverse(num);

}
}

Output:
Enter the number: 12345
After reversing the number: 54321

Comments

Popular posts from this blog

Multiple image upload to database and display from it

PHP Login and Registration script

String methods in java