C# Recursive Function to Calculate the Power of a Number

In this C# program, we define a recursive function called "Power" that calculates the result of raising an integer number to the power of another integer. This function will use recursion to multiply the base number by itself a number of times equal to the exponent. For example, if we call the function with `Power(5, 3)`, it should return 125, as 5 raised to the power of 3 is 5 × 5 × 5 = 125. The function will keep calling itself until the exponent reaches 1, at which point it will return the result.



Group

Functions in C#

Objective

1. Define a function named "Power" that accepts two integer parameters: the base number and the exponent.
2. Implement the function recursively by multiplying the base by itself and reducing the exponent by 1 in each recursive call.
3. The base case for the recursion should be when the exponent equals 1, in which case it returns the base number.
4. In the Main method, test the function by passing two integer values (base and exponent) and display the result.

Write a C# function that calculates the result of raising an integer to another integer (eg 5 raised to 3 = 53 = 5 × 5 × 5 = 125). This function must be created recursively.

public static void Main()

{
// Calculate 5 raised to the power of 3 using the recursive Power function
Console.Write( Power(5, 3) ); // This will print "125"
}

Example C# Exercise

 Copy C# Code
using System;

class Program
{
    // Main method where the program execution begins
    public static void Main()
    {
        // Calculate 5 raised to the power of 3 using the recursive Power function
        Console.Write( Power(5, 3) );  // This will print "125"
    }

    // Recursive function to calculate the power of a number
    public static int Power(int baseNum, int exponent)
    {
        // Base case: if the exponent is 1, return the base number
        if (exponent == 1)
        {
            return baseNum;  // Base case: return base number when exponent reaches 1
        }
        
        // Recursive case: multiply the base number by the result of Power with (exponent - 1)
        return baseNum * Power(baseNum, exponent - 1);  // Multiply base by the result of the next recursive call
    }
}

 Output

125

Share this C# Exercise

More C# Practice Exercises of Functions in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.