By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,789 Members | 1,190 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,789 IT Pros & Developers. It's quick & easy.

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

P: 2
int base;
int exp;
int answer = 1
for(int i = 0; i<n; i++)

This code above works, I just don't understand the functionality. "answer*=base" doesn't seem to have anything to do with "i" or "exp". I don't understand the logic behind it all.
Feb 5 '12 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 10K+
P: 12,422
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.
Feb 6 '12 #2

P: 2
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++)

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.??
Feb 6 '12 #3

Expert Mod 10K+
P: 12,422
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.
Feb 6 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.