next up previous
Next: Example: recursive implementation of Up: Unit 11 Previous: Inductively defined domains and

Example: recursive implementation of the sum between two integers

We exploit the following recursive definition of the sum between two non-negative integers:

sum(x, y) = $\displaystyle \cases{
x, & if \(y=0\)\cr
1 + \mathit{sum}(x, y-1), & if \(y>0\)}
$

Implementation:

public static int sum(int x, int y) {
  if (y == 0)
    return x;
  else
    return 1 + sum(x, y-1);
}


next up previous
Next: Example: recursive implementation of Up: Unit 11 Previous: Inductively defined domains and