Building An Exponent Method
Lesson 21Author : Afrixi
Last Updated : February, 2023
building an exponent method in C# using a for loop:
Copy code
public static double Exponent(double baseNum, int expNum)
{
double result = 1;
for (int i = 0; i < expNum; i++)
{
result = result * baseNum;
}
return result;
}
Let’s break down the code:
public static double Exponent(double baseNum, int expNum)
defines a method called Exponent
that takes two parameters: a double called baseNum and an int called expNum. The method returns a double.
double result = 1;
initializes a variable called result to 1. This is necessary because any number to the power of 0 is 1.
for (int i = 0; i < expNum; i++)
sets up a for loop that will iterate expNum number of times. For each iteration, the loop will perform the code block inside the curly braces.
result = result * baseNum;
multiplies the current value of result by baseNum and assigns the result back to result.
return result;
returns the final value of result after the for loop has completed.
Here’s an example of calling the Exponent
method:
Copy code
double result = Exponent(2, 3); // result = 8
In this example, we’re calling the Exponent method with a baseNum of 2 and an expNum of 3. The method calculates 2 to the power of 3 (which is 8) and returns the result, which is stored in the result variable.