Hi,
I am trying to work out how this function works but feel I am missing something as I can't understand the output.
If I use number = 5 and power = 3, it returns "5 to the 3th power is 125", which is what I expect the answer to be but I don't understand how it is getting that answer.
I understand that a function can call itself and I think I can understand some of the steps which I will outline below.
When the program gets to line 21, the function is called. The starting values are number = 5 and power = 3. From my understanding number will never change in main or in the function. However, power will never change in main but will change in the function.
When the function starts it prints the value of power and then tests if power == 1 on line 30, as it is 3 it jumps to the else statement and prints power = 3.
It then jumps to line 37, where the function is called again. When the function is called here the program jumps back to line 29 and prints value of power = 2 and tests if power == 1, which it dosn't. Therefore, program jumps to line 36 and prints value of power = 2.Program now jumps to line 37 where the function is called again.
The program now jumps back to line 29 and prints value of power = 1 and tests if power == 1, which it does. A message is printed that we are in if and returns n, which is 5.
So on line 37 we now have 5 * 5 = 25 and this value is assigned to answer. So how come the answer outputed by program is actually 125?
What am I missing?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
ULONG GetPower (USHORT n, ULONG power);
int main ()
{
USHORT number, power;
ULONG answer;
cout << "Enter a number: ";
cin >> number;
cout << "To what power: ";
cin >> power;
answer = GetPower (number, power);
cout << number << " to the " << power << "th power is " << answer << endl;
_getch();
return 0;
}
ULONG GetPower (USHORT n, ULONG power)
{
cout << "Entering function - power is: " << " " << power << endl;
if (power == 1)
{cout << "\nIn if START... " << n << " " << power << endl;
return n;}
else
//cout << "\nIn else START... Power is: " << power << endl;
//cout << (n * GetPower (n, (power-1))) << endl;
cout << "In else before return... Power is: " << power << endl;
return (n * GetPower (n, (power-1)));
}
|