200,063 views
25 votes
25 votes
Write a recursive function power(base, exponent) that when invoked returns

baseexponent.
For example, power(3, 4) = 3 * 3 * 3 * 3. Assume that exponentis an integer greater
than or equal to 1.
Then, write a demo program that uses the power function and test it out for a number of inputs.
Hint:
The recursion step would use the relationship
baseexponent = base * baseexponent–1
and the terminating condition occurs when exponent is equal to 1 because
base1 = base
heres the program i wrote:

#include
int power(int base,int exponent);
int main()
{
int e,b;
printf("enter base and exponent\\");
scanf("%d%d",&b,&e);
printf("%d rasied to %d is %d",b,e,power(b,e));

}
int power(int base,int exponent){
if(exponent==1)
return 0;

else
return base*power(base,exponent-1);
}

i wrote the program but there is an error it only prints zero with base and exponent how could i modify it?

User ImpopularGuy
by
2.2k points

1 Answer

18 votes
18 votes

Answer:

Step-by-step explanation:

Program and Result (PascalABC):

function Pow (x : real; n : integer) : real;

begin

if n = 0 then Pow := 1

else Pow := x*Pow(x,n-1);

end;

var a,b : real; k : integer;

begin

Write (' Real a = '); Readln (a);

Write (' Integer n = '); Readln (k);

b := Pow (a, k);

Write ( ' a ^ n = ', b );

end.

Write a recursive function power(base, exponent) that when invoked returns baseexponent-example-1
User Dimitar Mazhlekov
by
3.0k points