Thread: Can anybody show me why this works??

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    6

    Can anybody show me why this works??

    I found this recursive function code in a C book. I do not understand why it works. It seems to me that there is no variable in the function the keep up with the results, yet it works perfectly! Just curious.

    Thanks to anyone who can trace this program and show me what it is doing that I cannot see.

    tzuch

    Code:
    #include <stdio.h>
    
    int three_powered(int power);
    
    main(void)
    {
    	int a=0, fin;
    
    	puts("Enter an exponent:  ");
    	scanf("%d", &a);
    	
    	
    	printf("\n3 to the power of %d is %d",a,three_powered(a) );
    
    	puts("\n\nEnter a digit...");
    	scanf("%d", &fin);
    
    	return 0;
    
    }
    
    int three_powered(int power)
    {
    	if(power<1)
    	{
    		return 1;
    	}
    	
    	else
    	{
    		return(3*three_powered(power-1));
    	}
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    I have added some traces for your convinience... hope they will help you to understand what is going on
    Code:
    #include <stdio.h>
    
    int three_powered(int power);
    
    int main(void)
    {
    	int a=0, fin;
    
    	puts("Enter an exponent:  ");
    	scanf("&#37;d", &a);
    	
    	
    	printf("\n3 to the power of %d is %d",a,three_powered(a) );
    
    	puts("\n\nEnter a digit...");
    	scanf("%d", &fin);
    
    	return 0;
    
    }
    
    int three_powered(int power)
    {
    	if(power<1)
    	{
    		printf ("3^0 == 1\n");
    		return 1;
    	}
    	else
    	{
    		int res  = 3*three_powered(power-1);
    		printf ("3^%d == %d\n", power, res);
    		return(res);
    	}
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    6
    thank you very much vart. I should have done that but I'm fairly new at this.

    tzuch

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can't get window to show
    By GlitchGuy2 in forum Game Programming
    Replies: 2
    Last Post: 06-02-2009, 06:15 PM
  2. sudoku solver
    By manav in forum Game Programming
    Replies: 11
    Last Post: 02-03-2008, 10:38 PM
  3. good show on PBS tonite
    By axon in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 09-15-2004, 10:49 PM
  4. Window won't show
    By Toraton in forum Windows Programming
    Replies: 4
    Last Post: 11-10-2002, 08:07 PM
  5. That 70's show
    By xds4lx in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 09-27-2002, 04:16 AM