In this basic array problem, I need to add the sum or the value of the previous index of the array to the current index value using recursion.
For example, {5,3,1,2}
becomes {5,8,9,11}
.
Since the 0th index is the first index so it remains as it is.
I think my code is correct but instruction pointer is not flowing according to my dry run and the return statement (for the base condition) is not executing. Since I have my code in Java, after adding try-catch I'm getting output as expected. But adding try-catch is not the solution.
class kr1
{
public static void main(String[] args) {
int a[]= {5,1,3,9,5};
a=addr (a,0,a.length);
for (int i:a)
System.out.print (i +" ");
}
static int[] addr(int a[],int i,int n)
{
if (i==0)
addr(a,i+1,n);
if (i==n-1)
{
a[i] = a[i]+a[i-1];
return a ; //this return statement is not executing
}
//this below part is executing even if i has reached to n-1
a[i] = a[i] + a[i-1];
addr(a,i+1,n);
return a;
}
}