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?

Recommended Answers

All 2 Replies

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

commented: Stop giving people complete answers without comment, they're never going to learn anything -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.