twitter
    Find out what I'm doing, Follow Me :)

What Is Recursion?

Recursion is another of those programming techniques that seem very intimidating the first time you come across it, but if you will load and display the example program named recurson.c, we will take all of the mystery out of it. This is probably the simplest recursive program that it is possible to write and it is therefore a stupid program in actual practice, but for purposes of illustration, it is excellent.


main( )
{
int index;
index = 8;
count_dn(index);
}
count_dn(count)
int count;
{
count--;
printf("The value of the count is %d\n",count);
if (count > 0)

count_dn(count);
printf("Now the count is %d\n",count);
}



Recursion is nothing more than a function that calls itself. It is therefore in a loop which must have a way of terminating. In the program on your monitor, the variable "index" is set to 8, and is used as the argument to the function "count_dn". The function simply decrements the variable, prints it out in a message, and if the variable is not zero, it calls itself, where it decrements it again, prints it, etc. etc. etc. Finally, the variable will reach zero, and the function will not call itself again. Instead, it will return to the prior time it called itself, and return again, until finally it will return to the main program and will return to DOS.

For purposes of understanding you can think of it as having 8 copies of the function "count_dn" available and it simply called all of them one at a time, keeping track of which copy it was in at any given time. That is not what actually happened, but it is a reasonable illustration for you to begin understanding what it was really doing.