recursion problem c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream.h>
#include<conio.h>
using namespace std;
int re(int);
int main()
{
 int a, asd;
 cout<<"enter number\n";
 cin>>a;
 asd=re(a);
 cout<<asd;
 getch();
 return 0;   
}
int re(int a)
{
    int b;
 if(a==1)
 return ( 1 ) ; 
 else
  b=re(a-1);
  return (b);  
}

Hey, i was just trying to understand the concept of recursive funcition from the book of let us C by yashwant kanetkar.
Anyway, as far i understood ( i may be wrong) recursive function calls itself , and results as a loop like structure.
So in the above program, i want a username to input his no....
Then the program should print all the numbers from , the number itself to one. In decreasing order.
According to my logic, the number will get subtracted by one in each recursion the number should be subtracted by 1, and then it should be printed.
But, when the output has become 1, it should return 1 only.
For eg: when the username inputs 5.
The output should be:
54321

But, when i use the same theory to make a program to find out the factorial.
It works fine. I just multiply the number with its one decreased number.
for eg:
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
#include<iostream.h>
#include<conio.h>
using namespace std;
int re(int);
int main()
{
 int a, asd;
 cout<<"enter number\n";
 cin>>a;
 asd=re(a);
 cout<<asd;
 getch();
 return 0;   
}
int re(int a)
{
    int b;
    if(a==1)
    {
            return 1;
            }
            else
            {
 b=a*re(a-1);
 return b;  
}
}

Can you tell me where i am worng. I guess in the 1st program, the number gets printed only when the output is changed to 1. If this is the problem can you tell me how to fix it.
Thank You
Then the program should print all the numbers from , the number itself to one. In decreasing order. According to my logic, the number will get subtracted by one in each recursion the number should be subtracted by 1, and then it should be printed


But, that's not what you're doing. The only thing your printing is the last number returned by the recursive chain of calls.

1
2
3
4
5
6
void re(int a)
{
     cout << a ;
     if ( a > 1 )
         re(a-1) ;
}


The original program doesn't print all the numbers, it just decrements the number until it's == 1 and then returns 1, which is then printed. If you wanted to see each iteration's value, you'd need to add a cout to the re function.

You can't use the same recursive method to perform factorial - you need two variables for that - the factor and a running total. If you use 'a' as the total, it can't also be used as a decrementing counter.

Jim
Topic archived. No new replies allowed.