Recursion examples:
Example:1
C++ Program to calculate the factorial of a number using recursion.
Sol:
/* C++ Program to to calculate the factorial of a number using recursion */ #include<iostream> using namespace std; int fact(int n) { if (n==0) return(1); else return(n*fact(n-1)); } int main() { int n,f; cout<<"Enter any number "; cin>>n; f=fact(n); cout<<"the factorial of the number "<<n<<" is "<<f; return(0); }
/* Output */ Enter any number 5 the factorial of the number 5 is 120
Example:2
C++ Program to calculate and print sum of all the numbers upto a specified number.
Sol:
/* C++ Program to to calculate the factorial of a number using recursion */ #include<iostream> using namespace std; int sum(int n) { if (n==0) return(0); else return(n+sum(n-1)); } int main() { int n,s; cout<<"Enter any limit number "; cin>>n; s=sum(n); cout<<"the sum of the first "<<n<<" numbers is "<<s; return(0); }
/* Output */ Enter any limit number 5 the sum of the first 5 numbers is 15
Example:3
C++ Program to calculate and print product of all the numbers upto a specified number.
Sol:
Example:5
C++ Program to calculate and print the sum of two non-negetive integers.
Sol:
Example:4
C++ Program to take input for a number and print its table.
Sol: