E
E
Evsign2014-09-22 20:59:26
C++ / C#
Evsign, 2014-09-22 20:59:26

How to print numbers in reverse order without using arrays in c++?

Please help me decide, and most importantly, understand how to solve this task:
The standard input of the program is a sequence of space-separated positive integers ending in zero. It is required to print the same sequence in reverse order (without zero), separating the numbers with spaces. It is forbidden to use arrays (even if you are already familiar with them). (Hint: use recursion).
Sample Input :
1 2 3 4 0
Sample Output :
4 3 2 1
To begin with, I decided to try to implement at least the output of numbers in a given order. It just happened like this:

#include <iostream>

using namespace std;

int numb(int x){

    if (x != 0){
    	cout << x << " ";
    }
    return 0;

}

int main()
{
  int numbers = 0;

  while (cin >> numbers){
    numb(numbers);
  }

  return 0;
}

but I can’t understand where to splash further and how to put recursion here at all (When I insert recursion, a segmentation error almost always occurs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Morozov, 2014-09-22
@Evsign

press ctrl+F5 in studio, type for example "1 2 3 0" without quotes and hit enter ;)

#include <iostream>

void foo()
{
  int number;
  cin >> number;
  if (number != 0)
  {
                //фишка в том что:
    foo(); //сначала выполняется функция 
    cout << number << " "; // а после уже выполняется вывод
  }
}

int main(int argc, char *argv[])
{
  foo();
        return 0;
}

UPD:
1. recursion uses the call stack and the depth of recursion depends on the size of this stack
2. based on the previous point, you should not write code that is higher in production, it is better to use a loop and an array (or stack) that are forbidden
3. updated the signature of main, it doesn’t work should not affect the execution of the program, but
the result is more correct:
43c9f6240b4e4354b5e4e9e6c7114ff8.png

A
Alexey Trofimenko, 2014-09-25
@AdmAlexus

Is there a course on c++ on stepic.org? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question