C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 03-29-2008, 08:42 AM   #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));
	}
}
tzuch is offline   Reply With Quote
Old 03-29-2008, 08:47 AM   #2
CSharpener
 
vart's Avatar
 
Join Date: Oct 2006
Posts: 5,334
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("%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);
	}
}
__________________
If I have eight hours for cutting wood, I spend six sharpening my axe.
vart is online now   Reply With Quote
Old 03-29-2008, 09:03 AM   #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
tzuch is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 11:42 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22