Reverse A Number In Java Using For Loop
Reversing a number is a common programming challenge that involves reordering its digits from last to first. This operation can be useful in various scenarios, such as checking for palindromic numbers or performing specific mathematical manipulations. In this article, you will learn how to reverse a number in Java using a for loop.
Problem Statement
The core problem is to take an integer input and produce a new integer where the order of its digits is inverted. For example, if the input is 123, the output should be 321. This needs to be achieved programmatically, specifically using a for loop construct in Java.
Example
If the input number is 54321, the reversed number will be 12345.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java variables and data types: Specifically,
intfor integers. - Arithmetic operators: Modulo (
%) for getting the last digit and division (/) for removing the last digit. - Loops: The concept of iteration, particularly the
forloop. - Input/Output: How to read input from the console using
Scanner.
Use Cases or Case Studies
Reversing a number has several practical applications:
- Palindrome Check: Determining if a number reads the same forwards and backward (e.g., 121, 12321).
- Number Manipulation: Creating new numbers based on the reversed digits for specific algorithms.
- Data Encoding/Decoding: In some custom data formats, numbers might be stored or transmitted in a reversed order.
- Educational Exercises: A fundamental problem for beginners to practice loop constructs and arithmetic operations.
- Checksum Verification: Some checksum algorithms might involve reversing parts of a number.
Solution Approaches
We will focus on one primary approach using a for loop, as requested.
Approach 1: Using a for loop with arithmetic operations
This approach iteratively extracts the last digit of the number, appends it to a reversedNumber, and then removes the last digit from the original number until the original number becomes zero.
- One-line summary: Extract digits from the original number using modulo and division, building the reversed number digit by digit within a
forloop.
// Reverse a Number using For Loop
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize Scanner for user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt user to enter a number
System.out.print("Enter a number to reverse: ");
int originalNumber = scanner.nextInt();
// Step 3: Initialize variable to store the reversed number
int reversedNumber = 0;
// Step 4: Use a for loop to reverse the number
// The loop continues as long as originalNumber is not 0
// In each iteration, originalNumber is divided by 10 to remove the last digit
for (int tempNumber = originalNumber; tempNumber != 0; tempNumber /= 10) {
// Get the last digit of the current number
int digit = tempNumber % 10;
// Append the digit to the reversedNumber
// Multiply reversedNumber by 10 to shift existing digits to the left
// Then add the new digit
reversedNumber = reversedNumber * 10 + digit;
}
// Step 5: Print the original and reversed numbers
System.out.println("Original Number: " + originalNumber);
System.out.println("Reversed Number: " + reversedNumber);
// Step 6: Close the scanner
scanner.close();
}
}
- Sample output:
Enter a number to reverse: 12345
Original Number: 12345
Reversed Number: 54321
- Stepwise explanation for clarity:
- Input: The program first prompts the user to enter an integer, which is stored in
originalNumber. - Initialization: A variable
reversedNumberis initialized to0. This variable will store the result. forloop setup:
- The loop initializes a temporary variable
tempNumberwith theoriginalNumber. This is crucial because we need to modifytempNumberwithout alteringoriginalNumber(which we want to print later). - The loop continues as long as
tempNumberis not0. WhentempNumberbecomes0, it means all digits have been processed. - In each iteration,
tempNumberis divided by10(tempNumber /= 10). This effectively removes the last digit fromtempNumber.
- Extracting the last digit: Inside the loop,
int digit = tempNumber % 10;calculates the remainder whentempNumberis divided by10. This remainder is always the last digit oftempNumber.
- Example: If
tempNumberis123,123 % 10gives3.
- Building the reversed number:
reversedNumber = reversedNumber * 10 + digit;is the core logic for constructing the reversed number.
-
reversedNumber * 10shifts all existing digits inreversedNumberone position to the left, making space for the new digit. -
+ digitthen adds the extracteddigitto the rightmost position. - Example:
- Initially,
reversedNumber = 0. - First digit (e.g., 5 from 12345):
0 * 10 + 5 = 5.reversedNumberbecomes5. - Second digit (e.g., 4):
5 * 10 + 4 = 54.reversedNumberbecomes54. - And so on, until
reversedNumberis54321.
- Output: After the loop finishes,
reversedNumberholds the completely reversed number, which is then printed along with the original number. - Resource Cleanup: The
Scannerobject is closed to release system resources.
Conclusion
Reversing a number using a for loop in Java is a straightforward process that leverages basic arithmetic operations. By repeatedly extracting the last digit and rebuilding the number, you can effectively reverse its order. This technique is fundamental for various programming tasks and helps solidify understanding of loops