I am trying to print n to the power of p without using Math.Pow(). Here is the pseudocode:
get two integers n , p from the user
using a for-loop calculate the power function n ** p without using Math.Pow() method. output the result
using a while loop repeat the calculations output the result
using a do-while loop repeat the calculation output the result.
I have tried declaring the variables in numerous ways, and return total in the for loop.
using System;
public class Powers
{
public static void Main()
{
Console.WriteLine("Enter the base integer here:");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter exponent here:");
int p = int.Parse(Console.ReadLine());
for (int total = 1, counter = 1; counter <= p; ++counter)
{
total = total * n;
}
Console.Write($"{n} to the {p} power is {total}");
}
}
Variables defined in the for
clause exist only inside of the for
loop. If you want it to survive the loop, you have to define it outside:
int total = 1;
for (int counter = 1; counter <= p; ++counter)
{
total = total * n;
}
Console.Write($"{n} to the {p} power is {total}");