0
9.2kviews
Explain Recursion with example.
1 Answer
2
1.5kviews

Recursion: It is a method of programming where a function calls itself directly or indirectly. Recursion is used as an alternative to iteration. Recursion is simply the use of a function which, as part of its own execution code, invokes itself.

Recursion will be useful when same kind of job has to be continued for a finite no input or time.

Eg: calculating series, finding factorial etc. It reduces unnecessary calling of function.

Example : Factorial of a number

// pseudo code for factorial

int factorial (n) { If (n==0)

Return 1;

else

{

return n* factorial(n-1)

}

}

Let us see how factorial () method is used recursively to compute factorial of 3:

Factorial (3) = 3 * factorial (2)

= 3 * (2* factorial (1))

= 3 * (2* (1*1))= 6

Hence by using recursion, the same function is reused multiple times.

Please log in to add an answer.