The program calculates the power of a number using while loop and Math.Pow method in C#.NET.Program:
namespace DotNetMirror
{
class PowerOfNumber
{
static void Main()
{
double number, power, i = 1,sum = 1;
Console.Write("Enter a Number : ");
number = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Power : ");
power = Convert.ToInt32(Console.ReadLine());
while (i <= power)
{
sum = sum * number;
i++;
}
Console.WriteLine("{0} to the power {1} is: {2}", number, power, sum);
Console.ReadLine();
}
}
}
Using Math.Pow Method:
Math.Pow is inbuilt method from System.Math Namespace. Math.Pow method returns a specified number raised to the specified power.
namespace DotNetMirror
{
class PowerOfNumber
{
static void Main()
{
double number, power, sum = 1;
Console.Write("Enter a Number : ");
number = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Power : ");
power = Convert.ToInt32(Console.ReadLine());
sum = Math.Pow(number, power);
Console.WriteLine("{0} to the power {1} is: {2}", number, power, sum);
Console.ReadLine();
}
}
}
Output:
Enter a Number : 3
Enter Power : 4
3 to the power 4 is: 81
Note: We are using Double datatype for sum,number and power variables. Please check for data range and change the datatype accordingly.