Here is code to reverse an array using recursion
Using return rev(arr,++start,--end);
#include <iostream>
using namespace std;
void rev(int arr[],int start,int end)
{
if(start >= end)
{
return;
}
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
return rev(arr,++start,--end);
}
void reverse(int arr[],int size)
{
rev(arr,0,size-1);
}
Using rev(arr,++start,--end);
void rev(int arr[],int start,int end)
{
if(start >= end)
{
return;
}
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
rev(arr,++start,--end);
}
void reverse(int arr[],int size)
{
rev(arr,0,size-1);
}
They both give same output 7 6 5 4 3 2 1
What is the difference between using return and not using return with rev here?
returnis the last statement of the function, and the thing being "returned" isvoid. You can confirm this by comparing the compiler output. They are identical.rev()returnsvoid,return rev(arr,++start,--end);is equivalent in net effect torev(arr,++start,--end); return;or (since it is the last statement in the function before the closing}) torev(arr,++start,--end);