@Precious roy:
* The pow and pow2 in your main() are floats, even though the PowerOf() returns int. That is a legal conversion, but does not serve any purpose in this program.
* The
return PowerOf( a, b-- );
does same as:
1 2 3
|
int temp = PowerOf( a, b );
--b;
return temp;
|
Post-decrement returns a copy of the
old value.
Writing:
1 2 3 4 5 6
|
int PowerOf(int a, int b)
{
// your code here
return PowerOf(a, b--); // the actual recursion part
}
|
... creates impression that line 5 is as it should be and should stay unchanged.
Lets take again a=2, b=2. Lets ignore the effect of
post-decrement and pretend that
PowerOf(2,2) effectively has line:
return PowerOf(2,1);
Similarly, PowerOf(2,1) has line:
return PowerOf(2,0);
Furthermore, assume that slappy has added a condition on line 3 so that PowerOf(2,0) returns value 1.
Therefore, PowerOf(2,1) returns the value returned by PowerOf(2,0), i.e. 1.
Therefore, PowerOf(2,2) returns the value returned by PowerOf(2,1), i.e. 1.
This would be closer to what is needed.
1 2 3 4 5 6
|
int PowerOf(int a, int b)
{
// your code here
int sub = PowerOf(a, b--); // the actual recursion part
// your code here
}
|
@slappy:
This is a test program that uses your iterative (loop) "powerof" code.
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
|
#include <iostream>
#include <iomanip>
using std::setw;
using std::cout;
int Powerof( int a, int b ) {
int p=1;
int i;
for (i=1;i<=b;i++)
p=p*a;
return p;
}
int main()
{
cout << " ";
for ( int col = 1; col < 8; ++col ) {
cout << setw(1+col) << col << ' ';
}
cout << '\n';
for ( int row = 2; row < 10; ++row ) {
cout << row << ": ";
for ( int col = 1; col < 8; ++col ) {
cout << setw(1+col) << Powerof( row, col ) << ' ';
}
cout << '\n';
}
return 0;
}
|
Replace the code of Powerof with a recursive version.