Recursion in C Programming

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. Such a function is called recursive function.

 

Every recursive function should have the following two properties:

1)There should be some stopping condition in the function so that a function should stops its working.

2)The execution of the function should lead towards the stopping function

 

#include<stdio.h>

int y;

main()

{

int no,fact;

clrscr();

printf("\nenter any number");

scanf("%d",&no);

fact=recur(no);

printf("factorial value =%d",fact);

getch();

}

recur(int y)

{

int f;

if(y==1)

return(1);

else

f=y*recur(y-1);

return(f);

}

First Run when entered no=1                           Second Run when entered no=5

  Recursion in C                                        Recursion in C                                                                                       

Explanation..

In the first run when the number entered through scanf() is 1. The value of “a” is copied into y.

Since y turns out to be 1 the condition if(y==1) is true and hence 1 is returned.

When the number entered through scanf() is 5, main() would call recur with six times and recur will send back the computed value but before sending the computed value, recur() calls recur() and waits for a value to be returned. The arguments y in value is decreased by 1 and the process continue until condition fails.

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @