Thread: replacing a loop with recursion

1. replacing a loop with recursion

I'm trying to replace my a loop in a exponent function but I'm not sure how to go about doing it... thanks for any help
Code:
```double power(double a, double b)
{
double pow = 1;
int i = 1;
char flag = OFF;            /* the reason for using (char) is that it only takes up 1 byte */

if (b == 0)
return a;

if (b < 0)
flag = ON;

if (i <= b)                      /* this loop is what's messed up... */
pow *= power(a, i + 1);

if (flag == ON)
pow = 1 / power(a, -b);

return pow;
}```
that loop would normally be
Code:
```for (i = 1; i <= b; i++)
pow *= a;```
but that's my poor attempt at recursion...

2. try power(a, b-1);

i dun think you need i anymore

3. thanks, I finally got it. I still don't quite understand it, but it works fine.
Code:
```double power(double a, double b)
{
double pow = a;
char flag = OFF;            /* the reason for using (char) is that it only takes up 1 byte */

if (b < 0)
flag = ON;

if (b > 0)
pow *= power(a, b - 1);

if (flag == ON)
pow = 1 / power(a, -b);

if (b == 0)
pow = 1;

return pow;
}```

Popular pages Recent additions