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>
usingnamespace 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));
}
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.)