Java Program to Reverse a Number
Reversing a number is a common programming exercise that helps beginners understand loops, arithmetic operations, and number manipulation in Java.
In this tutorial, we will create a Java program that reverses a given number using a while loop.
By the end of this guide, you will understand how digit extraction and reconstruction work in Java.
Concept Overview
To reverse a number, we repeatedly extract the last digit using the modulus operator (%) and build the reversed number step by step.
We use a loop to continue this process until the number becomes zero.
Program
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num = num / 10;
}
System.out.println("Reversed Number: " + reversed);
}
}
Output
Enter a number: 1234
Reversed Number: 4321
Detailed Explanation
The program starts by importing the Scanner class for user input.
Inside the main() method, the user enters a number which is stored in variable num.
A variable reversed is initialized to 0 to store the reversed number.
The while loop runs until the number becomes 0.
Inside the loop, the last digit is extracted using num % 10.
The reversed number is built using reversed = reversed * 10 + digit.
The number is then reduced using num = num / 10.
Example Walkthrough
Let us consider an example where the user enters 1234.
Step-by-step process:
1234 → 4 → 43 → 432 → 4321
The output is displayed as 'Reversed Number: 4321'.
Applications
Reversing numbers is used in palindromic number checks, encryption algorithms, and data processing tasks.
Advantages of This Approach
This program helps beginners understand loops and digit manipulation.
It demonstrates how arithmetic operations can be used creatively.
Limitations
The program works only with integers and does not handle negative numbers or decimals.
Improvements You Can Make
You can extend this program to handle negative numbers.
You can also modify it to work with strings for reversing words.
Using methods can make the program more modular and reusable.
This Java program provides a strong understanding of loops and number manipulation, which are essential for programming logic development.
Codecrown