By Bimal Raj Paudel

Recursive program to calculate the power of the base


General Idea:

Recursive program to calculate the power of base using recursion
We always calculate a lot of a number raised to a power in Maths.
The general idea is that

  1. Anything raised to a power 0 is 1.
  2. If the power to be raised is not 0, then it is the same as multiplication of the base with the base raised to the initial power-1. Example:
  3. 2^0=0
  4. 2^5=2*(2^4)=2*2*(2^3)=2*2*2*(2^2)=2*2*2*2(2^1)=2*2*2*2*2(2^0)=2*2*2*2*2*1=32

PseudoCode:

power(a,b)
{
	if(a==0)
	{
		return(1);
	}
	
	else
	{
		return(a*power(a,b-1));
	}
}

Code in C:

#include<stdio.h>
#include<conio.h>

int power(int,int);
int main()
{
	int a; /*to  store base*/
	int b; /*to store power*/
	int p; /*to store the calculated value*/
	
	printf("Enter the base: ");
	scanf("%d",&a);
	
	printf("\nEnter the power: ");
	scanf("%d",&b);
	
	p=power(a,b); /*recursion function call */
	printf("\nThe power of %d raised to the power %d is: %d. ",a,b,p);
	getch();
	return(0);
}

int power(int x,int y)
{
	if(y==0)
	{
		return(1);
	}
	
	else
	{
		return(x*power(x,y-1));
	}
}

Output:

Recursive program to calculate the power of the base

Also Read: C Program To Generate Random Number Using Linear Congruential Method