1.3.1 Printing a Number1.3 Recursion1.3 Recursion1.3.2 Printing Anagrams

1.3.1 Printing a Number

We are given the problem of printing a non-negative integer number i in decimal representation by printing each individual digit. For instance, given i=235, we should print 2, 3, and 5 one at a time. The problem can be solved by the following recursive strategy:

  1. Base case: If i is in the range 0 ...9, print it directly (not the case for 235).
  2. Recursive case:
    1. Divide step: Divide i by 10 and solve the problem for this number (which prints 2 and 3).
    2. Conquer step: Print the remainder of diving i by 10 (5).

This can be directly implemented by the following Java method:

  // --------------------------------------------
  // printDecimal(i)
  // prints the decimal representation of i.
  //
  // Input:
  //   'i >= 0'.
  // Effect:
  //   Prints the decimal digits of 'i'.
  // --------------------------------------------
  static void printDecimal(int i)
  {
    if (i < 10)
      printDigit(i);
    else
    {
      printDecimal(i/10);
      printDigit(i%10);
    }
  }

The following method prints a single digit number:

  // ----------------------------------------------
  // printDigit(i)
  // prints i as a decimal digit.
  //
  // Input:
  //   '0 <= i <= 9'.
  // Effect:
  //   Prints the decimal digit represented by 'i'.
  // ----------------------------------------------
  static void printDigit(int i)
  {
    char ch = (char)(i + '0');
    System.out.print(ch);
  }

The decimal digits are represented by consecutive values in the Unicode character set. Therefore the (Unicode value of) character ch is computed by adding the given i to the (Unicode value of) character '0'.


© Wolfgang Schreiner; February 3, 2005

1.3.1 Printing a Number1.3 Recursion1.3 Recursion1.3.2 Printing Anagrams