When to use return in recursion

void bubblesort(int *arr, int n){
if(n==1){
return;
}
for(int i=0; i<n-1;i++){
if(arr[i]>arr[i+1]){
swap(arr[i], arr[i+1]);
}
bubblesort(arr,n-1); // if I put return bubblesort(), the function doesnt work
}
}

I do not understand when to use return for the recursive statement, because when we write another function for an appraoch without any loop we have to use the return statement:
void bubblesort2(int *arr, int n, int j){

if(n==1){
    return;
}
if(j==n-1){
    return bubblesort2(arr, n-1, 0);
}
if(arr[j]>arr[j+1]){
    swap(arr[j], arr[j+1]);
}
return bubblesort2(arr, n, j+1); // here the return works and without it i get an unsorted array.

}

hello @amanb25

a) there is mistake , this function call should be outside the for loop.

b) use of return .

  • if we encounter base case then we use return to return back to calling function.

  • we use return to return answer of subproblem to the calling function.

    • example. let say we want to compute sum of first n natural number.
      then we can write it as
      sum(n)=n+sum(n-1) ; // sum of first n number = n + sum of first n-1 natural number
      so what we do . we call sum(n-1) to get sum of first n-1 natural number and then add n .
      its recursive function should look like
      int sum(int n){
      if(n==1){
      return 1; // base case return is mandatory
      }
      int temp=sum(n-1); // this will return sum of first n-1 natural number which we store in temp
      return n + temp; // we add n to temp and return to calling function.
      }
      }
  • it also depends on algorithm u r implementing

thank you, I get it some what now maybe with some more practice I’ll be sure about it.

yeah ,recursion is tricky and demands practice.

one last thing, so in the code above its optional to use the return function in the recursive step because we basically are not returning anything.

yeah . . . . . . . . . . .

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.