next up previous
Next: Conditional counting of elements Up: Unit 11 Previous: Example: the last ones

Counting elements using recursion

We want to count elements read from a file. A recursive method to do so has the following structure:

read an element;
if (element is not valid)
  return 0;
else
  return 1 + result-of-the-recursive-call;

Example: Counting the number of lines of a file

public static int countLines(BufferedReader br) throws IOException {
  String s = br.readLine();
  if (s == null)
    return 0;
  else
    return 1 + countLines(br);
}


next up previous
Next: Conditional counting of elements Up: Unit 11 Previous: Example: the last ones