Thread: Don't uderstand how it's working

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    2

    Don't uderstand how it's working

    Hi, I don't understand how this recursion is working , I need to convert it to iterative function
    but without understanding i can't

    Code:
    double sequence(int n)
    {
    	double sum,i;
    	
    	if(n <= 30) return 2*n;
    	else
    	{
    		for(sum =0,i = 1;i <= 30;i++)
    			sum+= sequence(n-i);
    
    		return sum/30;
    	}
    }

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Looks to me like sum will be the value of n = 1...30 * 2^n . Maybe

    [edit] that's wrong, I missed the (n-i) bit

    I would throw some printf's in a couple places so you can watch it work.
    Last edited by MK27; 05-28-2010 at 09:38 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Get out a piece of paper and work through some cases. n < 30 are your base cases, so that's easy. Look at what happens for 31 and 32 and 33. Maybe also look at 61, 62, 63....

  4. #4
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Try working out what happens when this code is run.
    Code:
    #include <stdio.h>
    void level(unsigned int n);
    
    int main(void) {
      printf("In main. Going down!\n");
      level(4);
      printf("Back in main!\n");
      
      return 0;
    }
    
    void level(unsigned int n) {
      printf("Level %d, going down.\n", n);
      if (n > 0) {
        level(n - 1);
      }
      printf("Level %d, going up.\n", n);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function not working
    By sloopy in forum C Programming
    Replies: 31
    Last Post: 11-12-2005, 08:08 PM
  2. Program Not working Right
    By raven420smoke in forum C++ Programming
    Replies: 2
    Last Post: 09-16-2005, 03:21 AM
  3. Trying to eject D drive using code, but not working... :(
    By snowfrog in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2005, 07:47 PM
  4. x on upper right corner not working
    By caduardo21 in forum Windows Programming
    Replies: 1
    Last Post: 02-20-2005, 08:35 PM
  5. cygwin -> unix , my code not working properly ;(
    By CyC|OpS in forum C Programming
    Replies: 4
    Last Post: 05-18-2002, 04:08 AM