Automata Question – 3

Q3. You are required to fix all logical errors in the given code. You can click on Compile and
Run anytime to check the compilation/execution status of the program. You can use
System.out.printin to debug your code. The submitted code should be logically/syntactically
correct and pass all testcases. Do not write the main() function as it is not required.
Code Approach: For this question, you will need to correct the given implementation. We do
not expect you to modify the approach or incorporate any additional library methods.
The method calculateMatrixSum(int matrix[][]) of class MatrixSum accepts a two
dimensional array matrix as an input and returns the sum of odd elements whose i
th
and j
th
index are same.
The method compiles fine but fails to return the desired result for some test cases.
Your task is to debug the program so that it passes all test cases.
1 // You can print the values to stdout for debugging
2 public class MatrixSum
3 {
4 public static int calculateMatraxSum(int matrix[][])
5 {
6 int i, j, sum=0, row = matrix.length, column = matrix[0].length;
7 if ((row>0)&&(column>0))
8 {
9 for (i=0; i<row; i++)
10 {
11 sum =0;
12 for (j=0; j<column; j++)
13 {
14 if (i==j)
15 {
16 if (matrix [i][j]/2!=0)
17 sum += matrix[i][i];
18 }
19 }
20 }
21 return sum;
22 }
23 else
24 return sum;
25 }
26 }
Output. TestCase 1:
Status:
Correct
Expected:
5
Returned:
5
TestCase 2:
Ststus:
Correct
Expected:
17
Returned:
17This program was also checked on another testcases. 6 out of 6 passed.
1 // You can print the values to stdout for debugging
2 public class MatrixSum
3 {
4 public static int calculateMatrixSum(int matrix[][])
5 {
6 int i, j, sum = 0, row = matrix.length, column = matrix[0].length;
7 // if((row>0)&&(column>0))
8 // {
9 for(i=0; i<row;i++)
10 {
11
12 for(j=0; j<column; j++)
13 {
14 if(i==j)
15 {
16 // System.out.println(“in i,j”);
17 if(matrix[i][j]%2!=0){
18 // Syetem.out.println(“in i”+matrix[i][j]);
19 sum += matrix[i][j];
20
21 }
22 }
23 }
24 }
25 return sum;
26 /*}
27 else
28 return sum; */
29 }
30 }