Code:
#include<stdio.h>
/* A recursive function to get a^b
Works only if a >= 0 and b >= 0 */
int pows(int a, int b)
{
if(b)
return multiply(a, pows(a, b-1));
else
return 1;
}
/* A recursive function to get x*y */
int multiply(int x, int y)
{
if(y)
return (x + multiply(x, y-1));
else
return 0;
}
/* driver program to test above functions */
int main()
{
printf("\n 2^0 = %d", pows(2,0));
printf("\n 2^1 = %d", pows(2,1));
printf("\n 2^2 = %d", pows(2,2));
printf("\n 2^3 = %d", pows(2,3));
printf("\n 2^4 = %d", pows(2,4));
printf("\n 2^5 = %d\n", pows(2,5));
printf("\n 2^10 = %d\n", pows(2,10));
return 0;
}
output
Code:
[userx@devuan powers]$ ./a.out
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^10 = 1024
[userx@devuan powers]$
Write you own Power without using multiplication(*) and division(/) operators - GeeksforGeeks
but you'd better understand how it is really working, that is why I provided the link ...
how functions can call themselves, what values are being returned
putting printf in functions and looking at the values,
something like this to try and figure it out
Code:
/* A recursive function to get a^b
Works only if a >= 0 and b >= 0 */
int pows(int a, int b)
{ printf("b = %d\n", b);
if(b){
printf("%d\n", multiply(a, pows(a, b-1)));
return multiply(a, pows(a, b-1));
}
else
return 1;
}
I'm sure that teacher may know the answer is out there too. so you'd should make sure you're up to snuff on that.
it's hard being a teacher now days, the answers are on google.