Recursive Function
Apr 28, 2013 at 10:04am UTC
I'm practicing writing my own functions, recursive functions to be exact. My goal is to have it count up to a number, and then back down (a number the user inputs). It's required I have the function inside as well.
This is what I have so far. I expect it to display as...
input:4
1
2
3
4
4
3
2
1
But instead I get...
input:4
4
3
2
1
1
2
3
4
Here is my code. Please help. Thanks in advance.
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
#include <iostream>
using namespace std;
int display(double number);
int main()
{
double number, calls;
do {
cout << "Enter number " ;
cin >> number;
cout << endl;
calls = display(number);
cout << endl;
} while (1);
system("pause" );
return 0;
}
int display (double number)
{
int calls;
cout << number << endl;
if (number == 1)
calls = 1;
else
calls = display(number-1);
cout << number << endl;
return calls;
}
Last edited on Apr 28, 2013 at 10:11am UTC
Apr 29, 2013 at 5:24pm UTC
what your program does now is that it starts at 4(since that is the first input), and it keeps subtracting 1 until it has reached one.
if you want your desired output, then you should keep adding one, until it's 4.
you could do it this way
1 2 3 4 5 6 7 8 9 10 11 12 13
int display (double max, double start)
{
int calls;
cout<<start<<endl;
if (start == max)
calls = max;
else
calls = display(max, start+1);
cout<<start<<endl;
return calls;
}
I haven't tested the code myself, but I think it might work.
start is the number with what it should begin (in your case: 1).
Apr 30, 2013 at 12:44am UTC
That works. Thank you!
Topic archived. No new replies allowed.