Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive function of printing numbers in C++

How to write a recursive function of printing numbers first in increasing order and then in decreasing order .
Input: 5
Output: 1 2 3 4 5 5 4 3 2 1

I was trying to do it with single variable but it didn’t worked.

#include<iostream>
using namespace std;

void print(int n){
//base case:
 if(n==0){
 return;
 }

 print(n-1);
 cout<<n<<endl;
 }



int main(){
int n;
cin>>n;
print(n);


}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is one way of doing it:-

void func(int begin, int end)
{
    if(begin<=end)
    {
        cout << begin << ' ';
        func(begin+1, end);
        cout << begin << ' ';
    }
}

The reasoning behind having 2 parameters is: –

1 parameter to keep a track of how far the function is.
Another one to keep a track of where it is supposed to stop.

The output you seek can be obtained by calling the function as

func(1, 5);

Hopefully, the code is self explanatory.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading