Tuesday, November 10, 2015

Print Digits of A Number in Forward Or Backward Order in Java

Printing the separate digits of a number is another common example of using modulo operator.

Forward order display of separate digits of a number can be achieved with a recursive method and backward order display of separate digits of a number can be achieved with an iterative method in Java.


package basics;

public class PrintDigits {

 public static void printDigitsOfNumberInForwardOrder( int number )
 {
      if( number/10 > 0 )
          printDigitsOfNumberInForwardOrder(number/10);
  
      System.out.print(number%10+" ");
 }
 
 public static void printDigitsOfNumberInReverseOrder( int number )
 {
      while ( number > 0) {
          System.out.print(number%10+" ");
          number /= 10;
      }  
 }
 
 public static void main(String[] args) {
  
      int number = 1234;
      System.out.print("Digits of "+number+" in forward order are = ");
      printDigitsOfNumberInForwardOrder(number);
  
      number = 123429345;
      System.out.print("\nDigits of "+number+" in forward order are = ");
      printDigitsOfNumberInForwardOrder(number);
  
      number = 678123478;
      System.out.print("\nDigits of "+number+" in forward order are = ");
      printDigitsOfNumberInForwardOrder(number);
  
      number = 678123478;
      System.out.print("\nDigits of "+number+" in backward order are = ");
      printDigitsOfNumberInReverseOrder(number);
 }
}



Create a PrintDigits.java file in your workspace.

When the main method inside the PrintDigits class executed it is going to print :

Digits of 1234 in forward order are = 1 2 3 4
Digits of 123429345 in forward order are = 1 2 3 4 2 9 3 4 5
Digits of 678123478 in forward order are = 6 7 8 1 2 3 4 7 8
Digits of 678123478 in backward order are = 8 7 4 3 2 1 8 7 6

No comments:

Post a Comment