### recursion problem c++

 ``1234567891011121314151617181920212223`` ``````#include #include using namespace std; int re(int); int main() { int a, asd; cout<<"enter number\n"; cin>>a; asd=re(a); cout<

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:
 ``123456789101112131415161718192021222324252627`` ``````#include #include using namespace std; int re(int); int main() { int a, asd; cout<<"enter number\n"; cin>>a; asd=re(a); cout<

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.

 ``123456`` ``````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.