"Problem" outputs an integer in reverse order.
"Idea" there are three ways to output a number in reverse order:
1) using the while loop
2) Use for loop
3) Use recursion
Code
Program 1: Using the While loop
ImportJava.util.Scanner;classreversenumberwhile{ Public Static voidMain (String args[]) {intNum=0; intReversenum =0; System.out.println ("Input Your number and press ENTER:"); //This statement would capture the user inputScanner in =NewScanner (system.in); //captured input would is stored in number numnum =In.nextint (); //While Loop:logic to find out the reverse number while(num! = 0) {Reversenum= Reversenum * 10; Reversenum= Reversenum + num%10; Num= NUM/10; } System.out.println ("Reverse of input number is:" +reversenum); }}
Output Result:
145689986541
Program 2: Using a For loop
ImportJava.util.Scanner;classforloopreversedemo{ Public Static voidMain (String args[]) {intNum=0; intReversenum =0; System.out.println ("Input Your number and press ENTER:"); //This statement would capture the user inputScanner in =NewScanner (system.in); //captured input would is stored in number numnum =In.nextint (); /*For Loop:no initialization part as Num are already * initialized and No increment/decrement part as logic * num = NUM/10 already decrements the value of Num*/ for(; num! = 0; ) {Reversenum= Reversenum * 10; Reversenum= Reversenum + num%10; Num= NUM/10; } System.out.println ("Reverse of specified number is:" +reversenum); }}
Output Result:
5678911111198765
Program 3: Using recursion
ImportJava.util.Scanner;classrecursionreversedemo{//A method for reverse Public Static voidReversemethod (intNumber ) { if(Number < 10) {System.out.println (number); return; } Else{System.out.print ( number% 10); //Method is calling Itself:recursionReversemethod (NUMBER/10); } } Public Static voidMain (String args[]) {intNum=0; System.out.println ("Input Your number and press ENTER:"); Scanner in=NewScanner (system.in); Num=In.nextint (); System.out.print ("Reverse of the input number is:"); Reversemethod (num); System.out.println (); }}
Output Result:
5678901Reverseof the input number is: 1098765
Of course, if the number to be reversed has already been initialized, you don't have to enter it from the keyboard, such as:
class reversenumberdemo{ publicstaticvoid main (String args[]) { int num=123456789;//not from keyboard input, directly initialized to an integer value. int reversenum =0; while (num! = 0 ) { = Reversenum * Ten; = Reversenum + num%10; = Num/10; } System.out.println ("Reverse of specified number is:" +reversenum);} }
Getting Started with Java: Some beginners need to master the basic algorithmic program-Reverse output