1.

What is recursion? A recursive procedure should have two properties. What are they? What type of recursive procedure can be converted in to iterative procedure without using stack? Explain with example. 

Answer»

Recursion: - Recursion is defined as a technique of defining a set or a process in terms of itself. 

There are two important conditions that must be satisfied by any recursive procedure. They are: -

1. A smallest, base case that is processed without recursion and acts as decision criterion for stopping the process of computation and 

2. A general method that makes a particular case to reach nearer in some sense to the base case.

For eg the problem of finding a factorial of a given number by recursion can be written as 

Factorial (int n)

int x; 

if n = 0

return (1);

x = n - 1;

return ( n* factorial (x) );

}

in this case the contents of stack for n and x as [n, x] when first pop operation is carried out is as follows 

 [4, 3] [3, 2] [2, 1] [1, 0] [0, -] → top of stack.

Here the relation is simple enough to be represented in an iterative loop, and moreover it can be done without taking the help of stack. So such kind of recursive procedures can always be converted into an iterative procedure. 

The iterative solution for the above problem would be 

Factorial (int n) 

{

int x, fact = 1; 

for ( x = 1 ; x <= n ; x++ )

fact = fact * x;

return fact;

]

If there are no statements after the recursion call, that recursion can be converted to iterative programme very easily.for example:

void fff (parameters) 

if (condition) 

step1 

step2 

step3

fff (parameter)

}

whereas, if there are statements after a recursive call, a user stack will be required to convert them into iterative programme. for example:

void fff (parameters)

{

if (condition)

{

step1 

step2 

fff (parameters) 

step3 

step4 

fff (parameter)

}

}



Discussion

No Comment Found

Related InterviewSolutions