Write about Recursion in C Language?


The process of calling a function by itself is called recursion. The recursion process is applied for a task which can be explained in terms of itself.

To apply recursion 2 conditions must be satisfied:

1. The function should call itself directly or indirectly.

2. There should be a condition to stop the recursion process.

Ex: 

WAP to calculate factorial value of a given number using recursion.

#include
#include
int fact ( int);
main ( )
{
int n.f;
clrscr ( );
printf ( “enter n value”);
scanf (“%d”, &n);
f = fact ( n);
printf ( “factorial of %d is %d”, n,f);
getch ( );
}

int fact ( int a )
{
if ( a = = 1)
return ( 1);
else
return ( a * fact ( a-1);
}

Assume a =3, since the value of a is not 1, the statement

a * fact (a-1);

Will be executed with a =3; i.e

3 * fact (2);

Will be evaluated. The expression includes a call to “fact” with a =2. This call will return the following value:

2 * fact (1);

Once again, fact is called with n=1. This time, the function returns 1. The sequence of operations can be summarized as follows.

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

The recursion process makes use of stack to implement.

Related

C Language 8354343561479741342

Post a Comment

emo-but-icon

item