I am getting output for the below code as 3, but I think it should be 6. Can anyone explain the below code?

Viewed 22

Not able to understand what is happening here. The print statement is printing the output as 6, but the func function is return output as 3.

public class Main
{
   static int func(int[] arr,int n,int sum){
     if (n==0) return sum;
     sum+=arr[n];
     System.out.println("Inside functions "+sum);
     func(arr,n-1,sum);
     return sum;
   }
   public static void main(String[] args) {
     int[] arr={0,1,2,3,4,5,6,7,8,9};
     int ans=func(arr,3,0);
     System.out.println(ans);
   }
}
1 Answers

The problem was in returning the sum before saving the result from previous executions. So the sum in the first call of the function was never changed.

public class Main {
            static int sumArray(int[] arr, int i, int sum) {
                if (i == 0)
                    return sum;
                sum += arr[i];
                System.out.println("Inside function " + sum);
                sum = sumArray(arr, --i, sum); // saving result of the recursive function bevore returning
                return sum;
            }

            public static void main(String[] args) {
                int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
                int ans = sumArray(arr, 3, 0);
                System.out.println(ans);
            }
        }

I renamed some of the namings for readability.

Related