Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C++ Power of operation

Options
  • 02-02-2007 3:03pm
    #1
    Registered Users Posts: 159 ✭✭


    Hi i was wondering if someone could help me. for the life of me i can't work out how you would use a for loop to calculate one number to the power of another. i know that there is a library in c++ which can do this but i am supposed to use a for loop instead of using that library. If someone could point me in the right direction i would really appreciate


Comments

  • Closed Accounts Posts: 3,285 ✭✭✭Smellyirishman


    int power(int num, int n)
    {
       int result = num
       loop n times
          result = result * num 
       return result
    }
    

    With checks for the power = 0 and such things.


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Yeah fairly simple.
    int num,power,answer=0;
    
    cout << "Enter number: ";
    cin >> num;
    cout  <<"\nEnter Power: ";
    cin >> power;
    for(int k = 0; k < power; k++)
    {
        answer += num;
    }
    cout << "\nAnswer: " << answer;
    


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    And now we have another budding CS student who has just learned to copy and paste instead of figuring it out himself. :rolleyes:

    You're not really supposed to give full solutions for college problems, especially simpler ones like that ;)


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    Well it's probably okay if you give them code that's wrong...
    Webmonkey wrote:
    answer += num;


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Sorry about that should have known better.

    Hmm half asleep at the moment now with no compiler but can't see anything wrong with adding num to answer repeately.


  • Advertisement
  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Webmonkey wrote:
    Sorry about that should have known better.

    Hmm half asleep at the moment now with no compiler but can't see anything wrong with adding num to answer repeately.
    Well, i think the only person who'll learn anything out of this thread is you, the OP is a lost cause at this stage, he has the code and knows where the problem is in it ;)

    When you bring evaluate a ^ b (a to power of b), what do you get as your answer if a is 2 and b is 5? I can tell ya, it's not 12 :p


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Just realised my mistake in bed lastnight. I was just doing multiplying by repeating addition my apologies! Not editing my post, OP can have a bash at fixing it.


Advertisement