Answer the question
In order to leave comments, you need to log in
How to pop values from the C++ system stack using a recursive function?
Hello, there is a task in the tutorial that I can't solve.
You need to write a program that "flips" a sequence of positive integers. The input is a sequence of space-separated positive integers. The sequence ends with a null. You need to output this sequence in reverse order.
On the output, the number must also be separated by spaces. The terminating zero is just an indicator of the end of the sequence, it is not part of it, i.e. you don't need to take it out.
Implementation requirements: in this task it is forbidden to use loops, as well as additional memory: arrays, strings or containers (even if you are already familiar with them). You are allowed to have helper functions if you need them.
Hint: use recursion.
Sample Input: 15 26 1 42 0
Sample Output: 42 1 26 15
Stopped at this.
#include <iostream>
using namespace std;
int main() {
int nint;
int *addr = &nint;
cin >> nint;
if (nint == 0) {
cout << addr;
return 1;
}
return main();
}
Answer the question
In order to leave comments, you need to log in
#include <iostream>
using namespace std;
int main() {
int nint;
cin >> nint;
if (nint == 0) {
return 1;
}
main();
cout << nint << ' ';
}
Your score is 2 points. The C++ standard forbids calling main from within an application.
The use of recursion here is necessary just to reverse the sequence - printing should occur starting from the end of the line.
Consider an example of reversing an ASCIIZ string.
#include <iostream>
using namespace std;
void tnirp(const char* str)
{
if(*str)
{
tnirp(str+1);
cout << *str;
}
}
void print(const char* str)
{
if(*str)
{
cout << *str;
print(str+1);
}
}
int main()
{
const char str[]="Roses are red";
print(str);
cout << endl;
tnirp(str);
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question