Explain recursive function with an example

Estudies4you
Q42. What is recursion? Explain recursive function with an example.
Answer:

Recursion
Recursion is the process or technique by which a function calls itself. A recursive function contains a statement within its body, which calls the same function. Thus, it is also called as circular definition. Recursion can be classified as direct recursion and indirect recursion. In direct recursion, the function calls itself and in the indirect recursion, a function (f1) calls another function (f2), and the called function (f2) calls the calling function (f1).

Implementation of Factorial Using Recursion in C++
Recursive function to implement factorial is as follows,
int fact(int n) .
{
int f;
if(n==0 || n == 1)
f=1;
else
f=n* fact(n-1); /* Here fact function is calling itself*/
return f;
}
Example
Factorial of 3 using the above implementation is shown below,
Explain recursive function with an example in c++,c++ lecture notes,c++ notes,c++ study material,c++ previous question papers,oops using c++ notes,oops using c++ lecture notes,oops using  c++ study material,oops through c++ notes,oops through c++ study material,oops through c++ lecture notes,c++ notes jntuh,c++ notes jntu,jntu c++ notes,Advantages of Recursion in c++,Disadvantages of Recursion in c++,Implementation of Factorial Using Recursion in C++,Examples of recursion in c++,
Hence, the value of fact(3) is 6.
When a recursive call is made, the parameters and return address gets saved on a stack. The stack gets wrapped when the control is returned back.

Advantages of Recursion
  • Recursion solves the problem in the most general way as possible.
  • Recursive function is small, simple and more reliable than other coded versions of the program.
  • Recursion is used to solve the more complex problems that have repetitive structure.
  • Recursion is more. useful because sometimes a problem is naturally recursive.
  • For some problems it is easy to understand them using recursion.
Disadvantages of Recursion
  • Usage of recursion incurs overhead, since, this technique is implemented using function calls.
  • Whenever a recursive call is made, some of the system’s memory is consumed.
To Top