Question:
what is Recursion in C programming? explain with help of an example.?
Pushpendra C
2006-12-19 21:35:51 UTC
what is Recursion in C programming? explain with help of an example.?
Five answers:
2006-12-19 21:52:49 UTC
reoccurence of same is know as recursion.



Ex:



void mult(int n)



{

static int i=5,k=0;

k=i*mult(i-1);

return(k);

}



here when a funtion is called it wil come to first statment

k=i*mult(j);

it will try to multiply with i-1 i.e the funtion mult will call itself agian until and then calls agian then agian until i value is zero and the result is retured.



And the result is factorial of 5.
2016-12-16 18:16:51 UTC
Recursion In C Programming Example
Neil
2006-12-19 22:05:19 UTC
recursion is the notion of a function being able to call itself. The advantage of doing this lies in the fact that some problems are best described by themselves (only in a smaller form)



Example: Factorial(5)=5*Factorial(4)



It is supported in multiple programming languages including C



While I am sure that the other two people were hoping to help you, do not try to understand recursion from the examples they gave. Neither of the two people seemed to have compiler and run their code



A proper recursive program always has an exit condition and while the 2nd person has no exit condition, the 1st person's cade appears to have one (but actually does not)



A proper implementation of factorial method would be



int factorial(n) {

if (n>=1) {

return 1;

}

return n*factorial(n-1);

}



Read up a good C book with a proper explanation of recursion. It is one of the most powerful notions of computer science
Chris J
2006-12-22 15:21:33 UTC
A recursive function is one that can call itself if necessary. One area where this is generally useful is in traversing filesystem directories. This example deletes a directory on a Win32 system.



void DeleteDirectory( LPCSTR lpdir ){

CHARszFind[MAX_PATH];

HANDLEhFind;

WIN32_FIND_DATAFind;



sprintf( szFind, "%s*", lpdir );

hFind = FindFirstFile( szFind, &Find );

if( hFind == INVALID_HANDLE_VALUE )

return;

do{

if( Find.cFileName[0] == '.' )

continue;

if( Find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ){

sprintf( szFind, "%s%s\\", lpdir, Find.cFileName );

DeleteDirectory( szFind );

}

else{

sprintf( szFind, "%s%s", lpdir, Find.cFileName );

DeleteFile( szFind );

}

}while( FindNextFile( hFind, &Find ) );

FindClose( hFind );

RemoveDirectory( lpdir );

}





It annoys me that this thing doesn't preserve formatting. It makes it hard to read. Copy and paste that into your text editor and it'll look a lot neater.
csanon
2006-12-19 21:52:49 UTC
void recurse()

{

recurse();

}



Recursion is when something calls itself. In this case, the function recurse() calls itself within the function.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...