C# program to implement Power() method using recursion

Here, we are going to learn how to implement Power() method using recursion in C#?
Submitted by Nidhi, on September 10, 2020 [Last updated : March 19, 2023]

Implementing Power() Using Recursion

Here we will read the value on an integer number and power from the keyboard. Then find the power of the specified number using the recursive method.

C# code for implementing power() using recursion

The source code to implement Power() method using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to implement Power() method using recursion.
using System;

class Recursion
{
    public static int Power(int number, int power)
    {
        if (power == 0)
        {
            return 1;
        }
        else
        {
            return number*Power(number,power-1);
        }
    }

    public static void Main()
    {
        int num     = 0;
        int pow     = 0;
        int result  = 0;

        Console.Write("Enter the number: ");
        num = int.Parse(Console.ReadLine());

        Console.Write("Enter the power: ");
        pow = int.Parse(Console.ReadLine());

        result = Power(num, pow);

        Console.WriteLine("Result : "+result);
    }
}

Output

Enter the number: 4
Enter the power: 3
Result : 64
Press any key to continue . . .

Explanation

In the above program, we created a Recursion class. The Recursion class contains two static methods Main() and Power().

The Power() is a recursive method, here we calculated the power of a specified number. Here every recursive call decreases the value of power and we multiply the result of recursive call with the number. The method gets terminated when the value of power reaches the 0.

In the Main() method, we read the value of number and power and then calculate the power using the recursive method Power() and then print the result on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.