Thread: Recursion

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    207

    Recursion

    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
    Last edited by Lionmane; 06-01-2005 at 09:09 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  3. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  4. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 09:24 AM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 02:29 PM