Find power of a number using recursion in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 21-Aug-2018 12:07:12
Advertisements