Recursion

Recursion

·

2 min read

#include<iostream>
using namespace std;
void fun(int n){
    if(n == 0)return;
     fun(n - 1);
     cout<<n<<endl;
     fun(n - 1);
}
int main() {
    fun(3);
    return 0;
}


Print N to 1

#include<bits/stdc++.h>
using namespace std;

void func(int i, int n){

   // Base Condition.
   if(i<1) return;
   cout<<i<<endl;

   // Function call to print i till i decrements to 1.
   func(i-1,n);

}

int main(){

  // Here, let’s take the value of n to be 4.
  int n = 4;
  func(n,n);
  return 0;

}
// Output 

// 4
// 3
// 2
// 1

Print 1 to N

#include<bits/stdc++.h>
using namespace std;

void func(int i, int n){

   // Base Condition.
   if(i<1) return;
   cout<<i<<endl;

   // Function call to print i till i decrements to 1.
   func(i-1,n);

}

int main(){

  // Here, let’s take the value of n to be 4.
  int n = 4;
  func(n,n);
  return 0;

}

Output

4
3
2
1


Print Name N time using recursion

#include<bits/stdc++.h>
using namespace std;

void func(int i, int n){

   // Base Condition.
   if(i>n) return;
   cout<<"Raj"<<endl;

   // Function call to print till i increments.
   func(i+1,n);

}

int main(){

  // Here, let’s take the value of n to be 4.
  int n = 4;
  func(1,n);
  return 0;

}

Output

Raj
Raj
Raj
Raj


sum on N number

#include<bits/stdc++.h>
using namespace std;

void func(int i, int sum){

   // Base Condition.
   if(i<1)
   {
       cout<<sum<<endl;
       return;
   }

   // Function call to increment sum by i till i decrements to 1.
   func(i-1,sum+i);

}

int main(){

  // Here, let’s take the value of n to be 3.
  int n = 3;
  func(n,0);
  return 0;

}

Output

6