How to calculate Power of a number using recursion in C#?

To calculate power of a number using recursion in C#, we use the mathematical principle that n^p = n × n^(p-1). The recursive function calls itself with a reduced power until it reaches the base case.

Syntax

Following is the syntax for a recursive power function −

static long Power(int number, int power) {
    if (power == 0) {
        return 1;  // base case
    }
    return number * Power(number, power - 1);  // recursive case
}

How It Works

The recursion works by breaking down the power calculation into smaller subproblems. For example, to calculate 5², the function performs:

Recursive Power Calculation: 5² Power(5, 2) 5 × Power(5, 1) 5 × Power(5, 0) = 1

The key condition is: if the power is not equal to 0, the function calls itself recursively −

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

Example

using System;

public class Demo {
    public static void Main(string[] args) {
        int n = 5;
        int p = 2;
        long res;
        res = power(n, p);
        Console.WriteLine(res);
    }

    static long power(int n, int p) {
        if (p != 0) {
            return (n * power(n, p - 1));
        }
        return 1;
    }
}

The output of the above code is −

25

Using Multiple Test Cases

Here's an example demonstrating the power function with different values −

using System;

public class PowerCalculator {
    public static void Main(string[] args) {
        Console.WriteLine("2^3 = " + Power(2, 3));
        Console.WriteLine("4^0 = " + Power(4, 0));
        Console.WriteLine("10^4 = " + Power(10, 4));
        Console.WriteLine("3^5 = " + Power(3, 5));
    }

    static long Power(int number, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        return number * Power(number, exponent - 1);
    }
}

The output of the above code is −

2^3 = 8
4^0 = 16
10^4 = 10000
3^5 = 243

Key Rules

  • Base case: When power equals 0, return 1 (any number raised to power 0 is 1).

  • Recursive case: Multiply the number by the result of the same function with power reduced by 1.

  • Termination: The recursion stops when the power reaches 0.

Conclusion

Calculating power using recursion in C# follows the mathematical principle n^p = n × n^(p-1). The recursive function reduces the problem size with each call until it reaches the base case where the power equals 0, returning 1.

Updated on: 2026-03-17T07:04:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements