Find power of a number using recursion in C#


To find the power of a number, firstly set the number and the power −

int n = 15;
int p = 2;

Now create a method and pass these values −

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

Above, the recursive call gave us the results −

n * power(n, p - 1)

The following is the complete code to get the power of a number −

Example

 Live Demo

using System;
using System.IO;
public class Demo {
   public static void Main(string[] args) {
      int n = 15;
      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;
   }
}

Output

225

Updated on: 22-Jun-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements