Tuesday, 22 November 2016

Reverse of a number

Reverse number is displayed by writing it in reverse order. For example, reverse number of 123 is given as 321.

In given program, we use modulus (%) operator to obtain the digits of a number. The output of code is a number obtained by writing original number from right to left.


PROGRAM
class ReverseNum {

 int num;
 
 ReverseNum(int a) {
  
  num = a;
 }
 
 void showRev() {
  
  int n = num;
  int rev = 0;
  while(n>0)
  {
   rev = rev * 10 + (n%10);
   n = n / 10;
  }
  System.out.println("Reverse of "+num+" is "+rev);
 }
 
 public static void main(String args[]) {
  
  ReverseNum r = new ReverseNum(551);
  r.showRev();
 }
}
OUTPUT
C:\>javac ReverseNum.java
C:\>java ReverseNum
Reverse of 551 is 155

No comments:

Post a Comment