1

I would like too add two 2D arrays using a recursive method with this code:

public static int[][] x(int one[][],int two[][],int i,int j,int sum[][]){
    if(i==one.length-1 && j==(one[0].length-1)){
        return sum;
    }
    else if(j>one[0].length){
        j=0;i++;
        return x(one,two,i,j,sum);  
    }
    else {
        j++;
        sum[i][j]=one[i][j]+two[i][j];
        return x(one,two,i,j,sum);  
    }
}

but, this code doesn't work correctly. I did not understand.

Thanks!

3
  • 3
    Please check How to ask and edit your question. "This code doesn't work" is not a correct question. Commented Feb 6, 2018 at 9:26
  • can you provide and example? Commented Feb 6, 2018 at 9:28
  • You asked a nearly identical question earlier. Commented Feb 6, 2018 at 10:34

1 Answer 1

2

Is there any reason why you try to do it recursively? Iteratively is much easier in this case:

for (int i = 0; i < one.length; i++)
    for (int j = 0; j < one[i].length; j++)
        sum[i][j] = one[i][j] + two[i][j];

Of course you can get the same result recursively. Judging from your code I assume you want to call it like this: x(one, two, 0, 0, new int[one.length][one[0].length]).

Your main problem is that you move the indices already before doing the calculation and you return too early.

public static int[][] x(int one[][],int two[][],int i,int j,int sum[][]) {
    if (j == one[i].length) {
        if (i == one.length - 1)
            return sum;
        i++;
        j = 0;
    }
    sum[i][j] = one[i][j] + two[i][j];
    return x(one, two, i, j + 1, sum);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.