Skip to main content
gamedev.net
🔒 Locked

Recursive Function

Started by StephenNitro Oct 15, 2000 at 2:51 PM 1 replies 150+ views
Original Post
StephenNitro
StephenNitro
I'm trying to build a function that does the same job as pow(x,y) the idea of the function is to learn recursion, however its not working, anyone now why?
    

int power( int base , int exponent )
{

	if ( exponent == 1)
		return 1 ;
	else
		return  base *= power( base , exponent - 1 );
}



int main( )
{
	cout << power( 3 , 4 ) << endl;
	cout << pow( 3, 4 ) << endl; // Just for testing results 


	return 0;
}

    
Cheers Edited by - StephenNitro on 10/15/00 2:59:08 PM
Ironblayde
Ironblayde
Think about what is happening when you call the function. If you''re having trouble with a recursive function, write out what happens. For instance, your code does this:

Calling power(3,4)...
= 3 * power(3,3)
= 3 * 3 * power(3,2)
= 3 * 3 * 3 * power(3,1)
= 3 * 3 * 3 * 1
= 27 (wrong )

See the problem now? It''s your base case. When the exponent is 1, you would return ''base'' instead of returning 1. Or even better, use 0 as your base case, and return 1. That way your function will be able to handle a number raised the the 0th power, which is defined as 1. You should also add some functionality for negative powers, because as it stands, your function will recurse indefinitely if faced with a negative power, until your program crashes... which shouldn''t take too long.

-Ironblayde
 Aeon Software

"Down with Nazrix!" -pouya -Ironblayde
"Your superior intellect is no match for our puny weapons!"
Shannon Barber
Shannon Barber
Maybe we should make a forum dedicated to homework
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.