Iteration strange output

Feb 11, 2014 at 1:53am
Hey guys, this code works perfectly fine if n is 0 or 1, except for the fact that when it is any higher, at the end of every output is the square of x. This is the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int power1(int x, int n){

    int i = 0;
    if (n == 0){
        return 1;
        i++;}
    if (n == 1){
        return x;
        i++;}
    else {
        unsigned int temp;
        for (temp = x; n > 1; n--){
            temp *= x;
            i++;
            return temp;
        }
        cout << "# of multi's: " << i << endl;
    }
}


And the output is, for example a base number 5 and exponent 14:
1
2
3
5
14
25
Feb 11, 2014 at 2:34am
The return statement on line 15 should be after the loop, not in it. You also have a bunch of statements that will never be reached and therefore never executed (lines 6, 9 and 17).

Finally, 514 is too big to fit into an integer (so the result will be incorrect). Try some smaller numbers (55, 104, 36 etc...).
Feb 11, 2014 at 2:40am
Swap lines 15 and 16.
Feb 11, 2014 at 2:44am
Oh, sorry. I just put in 14 for emphasis. The suggestion of yours works, and I even moved cout << "# of multi's: " << i << endl; to after the brace in line 18, but I still can't get it to print the number of multiplications done in the process. Any suggestions?
Feb 11, 2014 at 2:47am
You need to move the cout statement to somewhere before the return statement (but also after the loop).
Feb 11, 2014 at 2:47am
Remember that when you return from a function, nothing else happens in that function. Program control returns to where the function was called.

So return temp; must come after cout << stuff; if you want to see that stuff.

Hope this helps.
Feb 11, 2014 at 2:57am
Yeah I changed it to what you guys said, and the output comes out fine, but is there not a way to make the calculated answer come first and then the number of multiplications?
Feb 11, 2014 at 3:17am
What is a power? ab is a multiplied by itself b times. So, 34 = 3 * 3 * 3 * 3. Now, your code would say that the# of multiplications is 3 (in the example, count the number of asterisks/ multiplication operators). So, if that is your desired output, simply print the exponent minus 1:

Note that the first output is the one that you have inside of the power1 function
1
2
3
4
5
b = 3;
p = 4;
result = power1(b, p);
cout<< result<< '\n';
cout<< "mults: "<< (p-1)<< '\n';
# of mult's: 3
81
mults: 3


No need to count the number of multiplications when we can easily calculate it :D
Feb 11, 2014 at 3:23am
Well that works lol. The program runs just like I'd want it to now. Thanks a bunch for all the help!
Topic archived. No new replies allowed.