Reputation: 43
I created a program to calculate the power of a number. Please look into the working code:
#include <stdio.h>
#include <stdlib.h>
int power(int,int);
int main()
{
int num,n;
scanf("%d %d",&num,&n);
printf("power of %d to %d\n",num,n);
printf("%d",power(num,n));
return 0;
}
int power(int num,int n)
{
int result=0;
if(n==0)
return 1;
if(n==1)
return num;
if(n%2!=0)
{
result=num*power(num,n-1);
}
else if(n%2==0)
{
result=power(num,n/2)*power(num,n/2);
//why this hangs when i replace this statement with power(power(num,n/2),2)
}
return result;
}
This program works fine as long as I don't replace the last statement with the one mentioned in the comments.
Could you please let me know the reason behind this abnormal behaviour?
Upvotes: 3
Views: 111
Reputation: 1371
This program works fine as long as I don't replace the last statement with the one mentioned in the comments.
Could you please let me know the reason behind this abnormal behaviour?
This isn't abnormal behavior.
power(power(num,n/2),2)
Is a recursive call where the base case is never reached because n == 2
therefore the else if clause for n % 2 == 0
is always going to be executed.
Upvotes: 1