# Thread: help, how would i change this recursive function

1. ## help, how would i change this recursive function

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);
}
}```

2. Originally Posted by webznz
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.

3. Hi,

One of the ways is mentioned below:

Code:
```int power(int n) {
int value = 1;

while(n > 0)
value *= 2;

return value;
}```
Regards
maverix

4. You forgot a little something...
Code:
```int power(int n) {
int value = 1;

while(n-- > 0)
value *= 2;

return value;
}```

5. Originally Posted by foxman
You forgot a little something...
Code:
```int power(int n) {
int value = 1;

while(n-- > 0)
value *= 2;

return value;
}```
Congrats, I think you guys just did a homework assignment.