0

Hello mates!

I'm having quite a bit of trouble reversing a set of integers using recursion.
The user enters a positive integer. The program then takes that integer, and lists 0,1,2...Number originally entered. The function SumTo lists zero to N, however I now need to reverse that list. Like this...

Enter a positive integer: 3
0, 1, 2, 3
3, 2, 1, 0

void SumTo(int Num){
    if(Num >= 1)
    SumTo(Num -1);
    cout << Num << " ";
   
}
void Reverse(int Num){
    SumTo(Num);
    if(Num != 0){
    Reverse(Num - 1);
    cout << Num << " ";
    }

Reverse is the reverse function, however it prints like this (although in all one line)
0123
012
01
0
123

Suggestions on how to only print 3 2 1 0?

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by ivailosp
0
#include <iostream>
using namespace std;

void Reverse(int x){
	cout << x << ' ';
	if (x == 0)
		return;
	Reverse(--x);
}

int main(int argc, char **argv) {
	Reverse(5);
	return 0;
}
-1
#include <iostream>
using namespace std;

void ToSum(int x){
	if (x == 0){
		return;
	}
	ToSum(--x);
	cout << x << ' ';
}
void Reverse(int x){
	cout << x << ' ';
	if (x == 0)
		return;
	Reverse(--x);
}
int main(int argc, char **argv) {
	ToSum(5);
	Reverse(5);
	return 0;
}

output:
0 1 2 3 4 5 4 3 2 1 0

Votes + Comments
Stop giving people complete answers without comment, they're never going to learn anything
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.