Design a class to input a number and print the number in reverse order java while loop and for loop
Answers
Answered by
2
Question:-
Design a class to input a number and print the number in reverse order in java using for and while loop.
Program:-
Using for loop.
import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number: ");
int n=sc.nextInt(),s=0;
for(;n!=0;n/=10)
s=s*10+n%10;
System.out.print("Reverse of the number is: "+s);
}
}
Using while loop.
import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number: ");
int n=sc.nextInt(),s=0;
while(n!=0)
{
s=s*10+n%10;
n/=10;
}
System.out.print("Reverse of the number is: "+s);
}
}
Similar questions
Environmental Sciences,
2 months ago
Physics,
2 months ago
Physics,
6 months ago
Science,
10 months ago