#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:
#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 wrong. 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