Advertisement

Recursive Function

Started by October 15, 2000 02:51 PM
1 comment, last by StephenNitro 24 years, 3 months ago
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
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!"
Advertisement
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

This topic is closed to new replies.

Advertisement