In: Computer Science
Describe a way to use recursion to add all the elements in a n × n (two dimensional) array of integers
(java)
Code:
public class Main
{
public int getSum(int[][] mat,int row,int column,int
rowMax,int columnMax)
{
if(row < 0 && column ==
0)
return 0;
if(row < 0)
{
row = rowMax -
1;
column = column
- 1;
}
return mat[row][column] +
getSum(mat,row - 1,column,rowMax,columnMax);
}
public static void main(String[] args)
{
int[][] mat = new int[][]{
{1,2},
{3,4}
};
Main sum = new Main();
int row = 2,column = 2,rowMax =
2,columnMax = 2;
int totalSum = sum.getSum(mat,row -
1,column - 1,rowMax,columnMax);
System.out.println("Sum : " +
totalSum);
}
}
OUTPUT: