recursive to count down

Hello all,
I am trying to write a recursive function to count down a number n to 1,
if the number n is 10, it should be: n, n-1, n-2, ..., 3, 2, 1;
This is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>
using namespace std;
int x(int n);
int main()
{
int n=10;
if (n==0)
{ cout<<"nothing "<<endl; }
else 
{ for (int i = n; i<=n; i--) 
{ cout<<n<<", "<<(x(n-1)); } }
return 0; }
int x(int n)
{
if (n>=0)
return (x(n-1));
}
A recursive function that counts down from n to 1 should print the value of n and then count down from n-1 to 1.

Does that help?
That's correct.
When i execute this code, it gives me an error.
you can check it here
http://codepad.org/66sHFooW
The problem is that function x has the return inside an if statement. add a return 0; at line 17 and it sould be fine.
Actually, the problem is that the function doesn't actually count down like it's supposed to. (And if you add a return 0; on line 17, it'll only ever return 0.)
All x(n) does is return the value of x(n-1), which returns the value of x((n-1)-1), and so on, so what actually ends up getting returned is simply x(0).

In reality, your function doesn't need to return anything -- it should be printing the values inside the function, not inside main. (See my last post about what the function should do.)

Also,
for (int i = n; i<=n; i--)
will loop for a long time. (But you don't really need the loop anyways, if you just print the values inside x.)
Last edited on
Topic archived. No new replies allowed.