next up previous
Next: Counting elements using recursion Up: Unit 11 Previous: Comparison between loop for

Example: the last ones will be the first ones

We want to read the lines of a file (which we access through a BufferedReader) and copy them to an output stream, inverting the order of the lines of the file.

By using recursion, this operation is straightforward.

public static void copyInverse(BufferedReader br, PrintStream p) throws IOException {
  String s = br.readLine();
  if (s != null) {
    copyInverse(br, p);
    p.println(s);
  }
}

The method copyInverse() cannot be realized easily in an iterative way. The reason is that, in order to print the lines in inverse order, we have to read and store all lines read in a suitable data structure, before starting to print. We will look at this example later on, and we will show how the memory locations associated to the local variables of the recursive activations act as temporary memory locations for the lines read from the file.

Note the difference between this type of recursion and the simpler cases seen before, in which we could easily obtain an iterative implementation (e.g., for the copy() method). The simple cases are those in which the last statement executed before the method terminates is the recursive call (tail recursion). Some compilers are able to detect the cases of tail recursion and replace the recursion with iteration, thus obtaining a more efficient machine code.

Instead, in general, a recursive implementation is less efficient than the corresponding iterative one, due to the necessity to handle the recursive calls (see later).


next up previous
Next: Counting elements using recursion Up: Unit 11 Previous: Comparison between loop for