# Thread: help with a recursiv programm

1. ## help with a recursiv programm

Okay guys this is a subject that is a bit confusing to me... so just take it easy ...

Write a recursive function power(base, exponent) that when invoked returns
base ,exponent
for example, power(3,4 )= 3*3*3*3.Assume that exponent is an integer greater than or equal to 1.And the termination condition occurs when exponent is equal to 1 because base 1 = base..

Code:
```#include <stdio.h>
#include <math.h>

int exponent ( int ,int ); //fucntion protoype

int main()
{
int cnt, result;
result = exponent (cnt, result );
for ( cnt =2; cnt <= 10; cnt++ ){
printf ("%d! = %d\n", cnt , result );
}

system("PAUSE");
return 0;
}

int exponent ( int a, int b )
{

if ( a <= 1 )
return 1;
else
return pow( (a*a),2);
}```

2. Something like

Code:
```int exponent ( int a, int b )
{
if ( b <= 1 )
return 1;
else
return a * exponent(a,b-1);
}```

3. When b=0...exponent(a,b) is still 1
so my codes

int exponent(int a,int b)
{
return b?a*exponent(a,b-1):1;
}

4. When b=0...exponent(a,b) is still 1
so my codes

int exponent(int a,int b)
{
return b?a*exponent(a,b-1):1;
}
Which requires one more function call than Salem's version. While this may not seem like a lot, if this is a function that were used many times, you would end up with unneeded overhead.

Quzah.

5. Originally posted by Salem
Something like

Code:
```int exponent ( int a, int b )
{
if ( b <= 1 )
return 1;
else
return a * exponent(a,b-1);
}```
shouldnt you return a when b==1 rather than 1

6. > shouldnt you return a when b==1 rather than 1

But I just copy/pasted the original author's code and made it recursive. Making it produce the right answer is an easy exercise for the reader

7. Originally posted by Salem
int exponent ( int a, int b )
{
if ( b <= 1 )
return 1;
else
return a * exponent(a,b-1);
}
Be careful this code should be changed to
Code:
```{
if (b==1)
return a; // ****not return 1
else
return a*exponent(a,b-1);
}```
You can return 1, if you check if (b==0).
Is that right?
But if I do it my own way, I will never use recursive programming for this case.