Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
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.
