+1 vote
in Class 12 by kratos

What is recursive function? Explain with a programming example.

1 Answer

+1 vote
by kratos
 
Best answer

A function that calls itself directly or indirectly again and again is called recursive functions and the process is termed as recursion. The most common example of a recursive function is the calculation of the factorial of a number. i.e., n! = (n) * (n – 1) Program:

void main()

{

int n;

int fact(int);

cout<<"Enter any number:";

cin>>n;

cout<<"The factorial is "<<fact(n);

}

int fact (int n)

{

int x;

if(n = = 0|| n = = 1)

return(1);

else

x = n*fact(n - 1);

return (x);

}

In the above example, the calling function main () gives the function call to fact () and control jumps from main () function to called function fact().

The argument ‘n’ value is compared with the base class ‘if (n == 1)’ if ‘true’ control will return back to calling function main() with the value 1.

If ‘False’, control will ** the statement which is after ‘else’ x = n fact ( n – 1);. here a function call is given to fact (n-1) with the parameter (n-1).

Now the calling function is fact () and called function is also fact(). The recursion ends when value of ‘n’ is 1 then the statement return (1) is initiated.

...