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

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.