Recursive function of printing numbers in C++

Advertisements

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);


}

>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.

Leave a Reply Cancel reply