E
E
Egor Mikheev2016-06-24 12:54:37
C++ / C#
Egor Mikheev, 2016-06-24 12:54:37

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

2 answer(s)
A
Andrey Burov, 2016-06-24
@BuriK666

#include <iostream>

using namespace std;
int main() {
    int nint;
    cin >> nint;
    if (nint == 0) {
        return 1;
    }
    main();
    cout << nint << ' ';
}

A
Armenian Radio, 2016-06-24
@gbg

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;
}

IDEONE Analyze
this example - comment each line
Pay attention to the difference between the text print and tnirp
To solve your problem, you need to slightly add to this program.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question