C program to Calculate the Power of a Number using Recursion

How to write a C program to find the power of a number using recursion ?

Power of a number tells us how many times a number needs to be multiplied with itself. Here we would learn how to write a C program to Calculate the Power of a Number using Recursion.

C-program-to-find-the-power-of-a-number-using-recursion-image

Syntax:

General code to find the power of a number in C.
int power(int base, int a) {
    if (a != 0)
        return (base * power(base, a - 1));
    else
        return 1;
}

In recursion there is a base case and recursive case or else the code won’t work. Here the base case is:

    else
        return 1;

The recursive condition is :

    if (a != 0)
        return (base * power(base, a - 1));

Steps to calculate the power of a number number:

  • Step 1: Start
  • Step 2: Declare the variables num, num2 and res.
  • Step 3: Read input num1 and num2 from the user or predefine it according to the need.
  • Step 4: Use the appropriate syntax that you need according to the requirements in the program.
  • Step5: Display the result in the stdout console.
  • Step 6: Program end.

Working:

Here we will learn to write a C program to Calculate the Power of a Number using Recursion.

Example 1 :

A simple program where we will find the power of a number that is predefined.

Run
#include<stdio.h>
int power(int n1, int n2);
int main()
{
    int num1=6, num2=4, result;
    result = power(num1, num2);
    printf("%d^%d = %d", num1, num2, result);
    return 0;
}

int power(int n, int m) 
{
    if (m != 0)
        return (n * power(n, m - 1));
    else
        return 1;
}

Output:

6^4 = 1296

Example 2 :

A simple program where we will find the power of a number that is predefined.

Run
#include<stdio.h>
int power(int n1, int n2);
int main()
{
    int num1=21, num2=3, result;
    result = power(num1, num2);
    printf("%d^%d = %d", num1, num2, result);
    return 0;
}

int power(int n, int m) 
{
    if (m != 0)
        return (n * power(n, m - 1));
    else
        return 1;
}

Output:

21^3 = 9261

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription