Help with recursive function?

Hello, I'm writing an assignment that prints out these number that change if the user entered number is a certain value (see code). This is done with a recursive function. Now I need to write the same recursive function and print the same output, only in reverse, and I'm not sure how to do that.

So my question is, how can I write the same recursive function, but change it so that is prints in reverse? Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;  

void reverseOJP() {

	// ?

}

int lengthOJP (int D, int count) {

	cout << endl << "The length of the OJP for " << D << " is " << count << endl;

	return 0;
}

void OJP(int D, int count, int refD) {


	if (D == 1) { // Base case

		count++; // counter
		cout << endl;

		reverseOJP(); // call and print reverse OJP
		lengthOJP(refD, count); // Once reverse is printed print length

	} else if ((D % 2) != 0) { // odd numbers

		D = ((D * 3) + 1); // if D is odd
		count++;
		cout << D << " ";

		OJP(D, count, refD); // Recursive Call

	} else { // even

		D /= 2;
		count++;
		cout << D << " ";

		OJP(D, count, refD);
	}
}

int main() {
	int D, refD, count = 0; // variables

	// user prompt and input
	cout << "Enter a positive integer: " << endl;
	cin >> D;

	// OJP output
	cout << "The OJP for " << D << endl;
	cout << D << " ";

	refD = D; // D reference for output purposes
	OJP(D, count, refD); // OJP call

	return 0;
}
Last edited on
If you want to reverse the order of the output, simply move the output after the recursive function call. You will find it impossible to put the newline and the call to lengthOJP in the right place, however. IMO, neither belonged in the function.


Topic archived. No new replies allowed.