Write A Program In Java To Reverse The Digits Of A Number Using While Loop
In this program, we will create a java program to reverse the digits of a number with the use of while loop.
In Java, a while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax for a while loop in Java is as follows:
while (condition) { // code to be executed as long as condition is true}
Here's how a while loop works:
- The condition is evaluated before executing the loop. If the condition is true, the loop body is executed. If the condition is false, the loop is skipped entirely and control passes to the next statement after the loop.
- The loop body is executed, which may modify the condition or perform other operations.
- The condition is evaluated again. If the condition is still true, the loop body is executed again. This process continues until the condition becomes false.
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: "); int number = scanner.nextInt();
int reversedNumber = 0; while (number > 0) { reversedNumber = reversedNumber * 10 + number % 10; number /= 10; }
System.out.println("Reversed number: " + reversedNumber); }}
Enter a number: 12345
Reversed number: 54321
Explanation
This program follows a similar structure to the previous
one, but it uses a more concise while loop that checks if the original number
is greater than 0. Inside the loop, we compute the reversed number in the same
way as before, and then divide the original number by 10 to remove the last
digit.
Once the while loop completes, we have the reversed number stored in the reversednumber variable, and we print it out to the console using System.out.println().