Power with For or While

Asked

Viewed 252 times

-3

I need a little help, how do I calculate the power using the for or while, I don’t want to use the Math.Pow function()

2 answers

1

Power is to multiply a stop several times itself. It makes there a base case that makes the number high to 1 with for or while then try to generalize, take the case of 0 as well. There are two very cool books that explain a good way these stops of dividing problems, are in English and use some bizarre things for those who do not like recursion. But take a look at "Structure and Interpretation of computer Programs", see at least until cap 2 or 3, it’s kind of difficult, also has the "How to design Programs", this one is easier.

  • Thank you very much!

1

c#

static void Main(string[] args)
{
    Console.WriteLine("Base: ");
    int myBase = int.Parse(Console.ReadLine());
    Console.WriteLine("Potencia: ");
    int myPow = int.Parse(Console.ReadLine());

    int result = 1;

    for (int i = 0; i < myPow; i++) result *= myBase;

    Console.WriteLine($"{myBase}^{myPow} = {result}");

    Console.ReadKey();
}

LINQ version for potentials greater than zero:

int result = Enumerable.Repeat(myBase, myPow).Aggregate((a, b) => a * b);
  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.