Complete the method code below so that the method will sum up the values of the
ID: 3574012 • Letter: C
Question
Complete the method code below so that the method will sum up the values of the odd-numbered columns of the array parameter foo as shaded in the table below. The number of rows and columns can be inferred from the array itself. The last column may or may not be an odd-numbered column. Make sure to account for this in your method. The code that you submit must be able to compile cleanly and execute inside a program.
Return the sum of those cells from the method.
You do not need to write a complete program, but include all relevant declarations you need.
Col 0
Col 1
Col 2
Col 3
Col 4
Col 5
Last column
Row 0
876
8
69886
1234
2354
3
…
9876
Row 1
97
64
875
5
456
467
…
76769898
Row 2
75
765
89
1231344
456
23
…
54
Row 3
76
57
96
66
67
23
…
765
…
…
…
…
…
…
…
…
Last row
123
3887
78783
773
1
2
…
4
Copy and paste this code into the answer box to start with:
/**
* method Name : sumArray
* Parameters : int array foo
* Task : sum odd columns in matrix
* Return : the summation of all odd columns
*/
public static int sumArray ( int foo [][] ) {
}
Col 0
Col 1
Col 2
Col 3
Col 4
Col 5
Last column
Row 0
876
8
69886
1234
2354
3
…
9876
Row 1
97
64
875
5
456
467
…
76769898
Row 2
75
765
89
1231344
456
23
…
54
Row 3
76
57
96
66
67
23
…
765
…
…
…
…
…
…
…
…
Last row
123
3887
78783
773
1
2
…
4
Explanation / Answer
OddRowColumn.java
import java.util.Arrays;
public class OddRowColumn{
public static void main(String[] args) {
int foo[][]= {{1,2,3,4,5}, {2,3,4,5,6}, {3,4,5,6,7},{4,5,6,7,8}, {5,6,7,8,9},{5,4,3,2,1} };
System.out.println("Input matrix is ");
for(int i=0; i<foo.length; i++){
System.out.println(Arrays.toString(foo[i]));
}
System.out.println("The sum of odd of columns: "+sumArray(foo));
}
public static int sumArray(int foo[][]){
int sum = 0;
for(int i=0; i<foo[i].length; i++){
if(i%2!=0){
for(int j=0; j<foo.length;j++){
sum = sum + foo[j][i];
}
}
}
return sum;
}
}
Output:
Input matrix is
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
[5, 4, 3, 2, 1]
The sum of odd of columns: 56
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.