In: Computer Science
In c++ Write a recursive driver function that will replace each of the odd values in a stack with the cube of the value.
#include <iostream>
#include <stack>
using namespace std;
//Recursive function
int oddv(int n) {
if (n % 2 == 0)
return n; //If even returns the same number
else
return n*n*n; //if odd returns the cube of the
number
}
//Displays the values in the stack
void showstack(stack <int> s)
{
while (!s.empty())
{
cout << '\t' << s.top();
s.pop();
}
cout << '\n';
}
//Driver class
int main() {
//Initializing the stack
stack <int> s;
stack <int> temp;
//Adding the values to the stack
s.push(10);
s.push(30);
s.push(20);
s.push(5);
s.push(3);
//Original Stack is
cout << "The stack is : ";
showstack(s);
//Storing the recursive function values in
temporary stack
while (!s.empty())
{
temp.push(oddv(s.top()));
s.pop();
}
//pushing back to the original stack
while (!temp.empty())
{
s.push(temp.top());
temp.pop();
}
//Printing the Stack
cout << '\n';
cout << "The stack is : ";
showstack(s);
return 0;
}