I have a simple recursion program that I copied out of a book. It works fine, but I'm still having trouble understanding exactly what goes on during recursion. I tried inserting printf statements in my code to see what was going on, but it only confused me more... :-(
Code:
#include <stdio.h>
long double factr (long double n);
void main ()
{
long double highest;
do
{
printf ("\n\nType '0' to quit.");
printf ("\n\nPlease specify a max range to calculate factorials.\n");
scanf ("%Lf", &highest);
if (highest > 0)
{
factr (highest);
}
} while (highest > 0);
printf("\n\n");
highest = 0;
}
long double factr (long double n)
{
long double answer;
printf ("Start Recursion! %d %d\n", n, answer);
if (n == 1) return (1);
answer = n * factr (n-1); //recursive call
printf ("\n%g %g", n, answer);
return (answer);
}
What I don't understand is why the "Start Recursion!" prints before any calculations are made & how it's able to print out the correct answers!?
mw