How do I raise any number x to a positive power n using a for loop?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • amandastanko
    New Member
    • Feb 2012
    • 2

    #1

    How do I raise any number x to a positive power n using a for loop?

    int base;
    int exp;
    int answer = 1
    for(int i = 0; i<n; i++)
    {answer*=base}


    This code above works, I just don't understand the functionality. "answer*=ba se" doesn't seem to have anything to do with "i" or "exp". I don't understand the logic behind it all.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    It won't work. At least not if that's all the code there is. It won't work unless somewhere else n is set to exp.

    Comment

    • amandastanko
      New Member
      • Feb 2012
      • 2

      #3
      Excuse me, I wrote the code wrong. n is supposed to be the exp.
      So it goes:

      int base;
      int exp;
      int answer = 1;
      for(int i=0; i<exp; i++)
      {answer*=base;}

      This format works, and when output the exponent of any base is printed.
      I just don't understand {ans*+base;}
      ... how does this simple statement work? It leaves out both i and exp.??

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        answer *= base is the same thing as answer = answer * base. i and exp doesn't have to be used in the actual calculation. It's just there to make sure base is multiplied the correct number of times. 2 to the power of 3 is 8. 2 is the base, 3 is the exp. But to calculate it, it's 2 * 2 * 2. There's no need to actually use exp in the calculation.

        Comment

        Working...