Very Basic Recursion Programs



A recursion, simply, is a function calling itself.


1. Finding factorial of a number

Here we're assuming that our number will be either positive or zero.

#include<iostream>

using namespace std;

//FACTORIAL

int factorial(int n){

if(n==0) return 1;

else

return n*factorial(n-1);

}

//MAIN

int main()

{

cout<<factorial(0);

return 0;

}


2. Finding the Sum of First "n" numbers

#include<iostream>

using namespace std;

int temp=0;  //global variable

//SUM function

int Sum(int n){

temp+=n;

if(n>0)

Sum(n-1);

if(n<=0)

return -1;

return temp;

}

//Main function

int main()

{

cout<<Sum(100); //here we are finding sum of first 100 numbers

}

Comments