next up previous
Next: Example: the last ones Up: Unit 11 Previous: Example: maximum of positive

Comparison between loop for reading and recursive reading

Structure of the loop for reading:

read the first element
while (element is valid) {
  process the element;
  read the following element;
}

Recursive reading:

read an element
if (element is valid) {
  process the element;
  call the reading method recursively;
}

Example: Copy of a file (accessed through a BufferedReader) to an output stream.

Iterative implementation:

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

Recursive implementation:

public static void copy(BufferedReader br, PrintStream p) throws IOException {
  String s = br.readLine();
  if (s != null) {
    p.println(s);
    copy(br, p);
  }
  // else don't do anything
}


next up previous
Next: Example: the last ones Up: Unit 11 Previous: Example: maximum of positive