into an iterative one, what steps would you take..
Code:int power (int n){ int (n == 1){ return 2; }else{ return 2*power(n-1); } }
This is a discussion on help, how would i change this recursive function within the C Programming forums, part of the General Programming Boards category; into an iterative one, what steps would you take.. Code: int power (int n){ int (n == 1){ return 2; ...
into an iterative one, what steps would you take..
Code:int power (int n){ int (n == 1){ return 2; }else{ return 2*power(n-1); } }
First, you probably meant "if (n == 1)" not "int (n == 1)".
Well, figure out what it computes.
If you pass it 1, it returns 2.
If you pass it 2, it returns 2 * power(1) = 2 * 2 = 4.
If you pass it 3, it returns 2 * power(2) = 2 * 2 * power(1) = 2 * 2 * 2 = 8.
Hopefully it becomes clear what to do.
Hi,
One of the ways is mentioned below:
RegardsCode:int power(int n) { int value = 1; while(n > 0) value *= 2; return value; }
maverix
You forgot a little something...
Code:int power(int n) { int value = 1; while(n-- > 0) value *= 2; return value; }