# Can Anybody help me out, in converting my code to iterative method.

• 03-14-2011
Can Anybody help me out, in converting my code to iterative method.
Hello,

I am new on programming, is currently using dev c++. I was asked to write a method to find x^y, where y is a power of x. Using recursive and iterative solution. I already have the recursive one, but I don't know how to make it to iterative. Here is my recursive solution.
Code:

```#include<stdio.h> int power (int, int); int main () {         int base, exp, result;                 printf("Please enter a base number\n");         scanf("%d",&base);         printf("Please enter a exponent number\n");         scanf("%d",&exp);         result = power(base, exp);         printf("\n The result is:%d\n",result);                 system("pause");     return 0; } int power (int base, int exp) {   if(exp >= 1)       return base * (power(base,exp - 1));   else       return 1; }```
Help would highly be appreciated. Thanks in advance..
• 03-14-2011
Clairvoyant1332
Use a loop to keep multiplying the base exp number of times
• 03-14-2011
Yeah, I tried to used loop and got this code....

#include<stdio.h>

int main()

{
int base, exp, result;

scanf("%d",&base);
scanf("%d",&exp);

int i = 1;
for (i=1; i < exp; i++)
result=result*base;
printf("\n The result is:%d\n",result);

system("pause");
return 0;
}

The problem is I can't get the exact value when inputting a base of 4 and exponent of 4.. it gives a result of 128, it should be 256.... can somebody help me please... Thanks
• 03-14-2011
Clairvoyant1332
Take a look at the loop condition. How many times does it run?

Also, I don't see an initial value for result. You're lucky the result isn't more off than it is.
• 03-14-2011
Salem
Also, take at look at your first post (as edited by me), and see how much better the code looks.