Recursion Examples

Feb 28, 2014
During my college days, we simply refer to recursion as a method that calls itself.

Here's a simple program.
Our goal is to compute the factorial of positive integer N.
A non-recursive definition would look like this:

int val = 1;
for(int x=1; x <= N; x++)
{
 val = val * x;
}

But when we define a recursive method, it would be something like this:

int factorial(int N)
{
 if(N == 1)
  return 1;
 else
  return N * factorial(N-1);
}

Here are other examples of recursive methods.

/** Getting the product of two integer values **/

int product (int x, int y)
{
 if (y == 1)
  return x;
 else
  return x + product(x, y-1);
}

/** Displaying digits of a given number in a separate line **/

void display(int x)
{
 if (x >= 10)
  display(x/10);

 System.out.println(x%10);
}

/** Getting the sum of the square from 1 to n **/

int sumofsquare(int n)
{
 if(n == 1)
  return 1;
 else
  return (n*n) + sumofsquare(n-1);
}

/** Prints odd numbers between 1 to N **/

void printodd(int N)
{
 if (N!=1)
 {
  printodd(N-1);
  if(N%2 != 0)
   System.out.println(N);
 }
}

/** Calculates the length of a linked list **/

int length(NodeOp p)
{
 if(p == tail)
  return 1;
 else
  return 1 + length(p.next);
}

1 comment: