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

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.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.