Exercise
Function Power Local Variables
Objective
Write a C# function named "Power" to calculate the result of raising an integer number to another (positive integer) number. It must return another integer number. For example. Power(2,3) should return 8.
Note: You MUST use a repetitive structure, such as "for " or "while", you cannot use Math.Pow.
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to calculate the power of a number raised to another number
// It uses a for loop to multiply the base number by itself 'exponent' times
public static int Power(int baseNumber, int exponent)
{
// Local variable to store the result of the power calculation
int result = 1;
// Repetitive structure (for loop) to multiply the base number by itself 'exponent' times
for (int i = 0; i < exponent; i++)
{
result *= baseNumber; // Multiply result by baseNumber on each iteration
}
// Return the result of the power operation
return result;
}
// Main method where the Power function is called
public static void Main()
{
// Declare two integers: base and exponent
int baseNumber = 2;
int exponent = 3;
// Call the Power function and print the result
Console.WriteLine("The result of {0} raised to the power of {1} is: {2}", baseNumber, exponent, Power(baseNumber, exponent));
}
}