In this program, you’ll learn to calculate the power of a number using a recursive function in C#.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pow_recursion { class Program { public static int power(int n, int powerRaised) { if (powerRaised != 0) return (n * power(n, powerRaised - 1)); else return 1; } static void Main(string[] args) { int num = 2, powerRaised = 3; int result = power(num, powerRaised); Console.Write("{0}^{1}= {2}", num, powerRaised, result); Console.ReadKey(); } } } |
In the above program, you calculate the power using a recursive function power().
Output: