To find power of a number using recursion

To find power of a number using recursion

Question:

Write a program to find the power of a number using recursion.

Logic:

  • Get the base value and also power value from the user.
  • Then the base number multiplies with itself for power value.
  • And return the calculated value.

Algorithm:

  1. Get the base value as m and also power value as n.
  2. Then m multiplies with itself for n times as recursively.
  3. Return the calculated value the n reaches 0.

Program:

[code lang=”c”]
#include<stdio.h>
void main()
{
int m,n;
clrscr();
printf("enter the base no:");
scanf("%d",&m);
printf("enter the power no:");
scanf("%d",&n);
/*the value m and n passes as an argument into the function*/
printf("the value of number is: %d",pow(m,n));
getch();
}
int pow(int m,int n)
{
if(n!=0)
{
return m*pow(m,n-1); //the value m mutiplies itself of n times then return value
}
else
{
return 1; //returns when value is zero
}
}
[/code]

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *