What is the base case in this Recursion?

#include
using namespace std;

void fun(int x)
{
if(x > 0)
{
fun(–x);
cout << x <<" ";
fun(–x);
}
}

int main()
{
int a = 4;
fun(a);
return 0;
}

Can anyone explain this recursion?

The Recusrsive Call happens only if the number is positive i.e. > 0 .
So the base case is itself n<=0 ( to stop our recursion ) .

4 Likes

I would slightly modify this code which would surely help you catching up with the base case.

#include<iostream>
using namespace std;

void fun(int x){
**if(x<=0)**
**return;**
fun(-x);
cout<<x<<" ";
fun(-x);
}

@messi1711’s answer can be explained with this code.
Hope you understood.
Cheers!

3 Likes

YES !!!

1 Like

I think you should include “x<=0” instead of “x<0” in the base case.

2 Likes

That would be much better. Thanks for the correction mate. Cheers!

1 Like

A base condition is basically the smallest sub-problem you can solve. In this case, when x>0 you divide it into sub-problems, so this is not your base condition. For values of x<=0 you know you do not have to perform operations, so they are your smallest sub-problems which you know how to solve, therefore it is your base condition.

1 Like

Thank you! It was helpful

Thank you

Thanks!

1 Like