Tags:C Interview Question, C++ Questions | 198 views
Here’s a simple function that does an infinite loop. It prints a line and calls itself, which again prints a line and calls itself again, and this continues until the stack overflows and the program crashes. A function calling itself is called recursion, and normally you will have a conditional that would stop the recursion after a small, finite number of steps.
void infinite_recursion()
// don't run this!
{
printf("Infinite loop!n");
infinite_recursion();
}
A simple check can be done like this. Note that ++depth is used so the increment will take place before the value is passed into the function. Alternatively you can increment on a separate line before the recursion call. If you say print_me(3,0); the function will print the line Recursion 3 times.
void print_me(int j, int depth)
{
if(depth < j)
{
printf("Recursion! depth = %d j = %dn",depth,j);//j always the same
print_me(j, ++depth);
}
}
Recursion is most often used for jobs such as directory tree scans, seeking for the end of a linked list, parsing a tree structure in a database and factorising numbers (and finding primes) among other things.
RSS feed for comments on this post · TrackBack URI
Leave a reply