Share
Explore BrainMass

C++ recursion program

1. Modify this pop() function, so that it uses recursion.

int Stack::pop()
{
if (isEmpty())
{
cerr << "Attempting to Pop from an Empty stack!!" << endl;
return -1;
}
else
{
int temp = nodes[curTop];
curTop--;
return temp;
}

}

2. Rewrite the following power() function so that it uses recursion. Provide a function main to test the implementation.

power.cpp

#include <iostream>

using namespace std;

int power(int number, int exponent)
{
int retval = 1;
for (int i=0; i < exponent; i++)
{
retval = retval * number;
}
return retval;
}

int main(int argc, char **argv)
{
cout << power(2, 3) << endl;
cout << power(3, 6) << endl;
cout << power(4, 9) << endl;

return 0;
}

Attachments

Solution Preview

Dear Student,

Part 2 is simple:

int power(int number, int exponent)
{
int retval = 1;

if (exponent == 1)
{
retval = number;
}
else if (exponent > -1)
{
exponent--;
retval = number * (power(number,exponent));
}
return retval;
}

As for Part ...

Solution Summary

C++ recursion implementation for pop() and power() functionality

$2.19