+1 vote
in Class 12 by kratos

What is recursive function? Give the syntax and example for it.

1 Answer

+5 votes
by kratos
 
Best answer
  1. A function that calls itself directly or indirectly, again and again, is called recursive functions and the process is termed as recursion.

  2. A function is called ‘recursive’ if a statement within the body of that function calls the same function.

  3. The most common example of a recursive function is the calculation of the factorial of a number. i.e., n! = (n) * (n-1) In the above formula, the second part (n-1)! is calling the formula again.

Program:

void main()

{

int n, factorial;

int fact(int);

cout<<"Enter any number:";

cin>>n;

factorial = fact(n);

cout<<"\n The factorial is "<<factorial;

}

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 co, To 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().

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.

...