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
Show 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