Example of output: Sum by rows: 45 Sum by columns: 45 Sum reversed diagonal elem
ID: 3741095 • Letter: E
Question
Example of output:
Sum by rows: 45
Sum by columns: 45
Sum reversed diagonal elements: 15
/**********************************Problem2.java **************************************************/
public class Problem2 {
int[][] myArray;
//Constructor: Initialize myArray with the given
//vallues provided from the given square above.
public Problem2() {
}
//sum All Elements by rows: Write your code below
public int sumAllElementsbyRows() {
}
//Sum Reversed Diagonal Elements: Write your code below
public int sumAllReversedDiag() {
}
//sum All Elements by columns: Write your code below
public int sumAllElementsbyColumns() {
}
public static void main(String[] args){
Problem2 myProblem2 = new Problem2();
System.out.println("Sum by rows: " + myProblem2.sumAllElementsbyRows ());
System.out.println("Sum by columns: " + myProblem2.sumAllElementsbyColumns());
System.out.println("Sum reversed diagonal elements: " + myProblem2.sumAllReversedDiag());
}
}
Explanation / Answer
/**** I have provided the complete program . First i have created the 2D array which you have given in the constructor. Then Provided all three methods ****/
package learning;
public class Problem2 {
int[][] myArray;
//Constructor: Initialize myArray with the given
//vallues provided from the given square above.
public Problem2() {
myArray = new int[3][3];
int num = 1;
for(int i=0; i<3;i++){
for(int j =0; j<3;j++){
myArray[i][j] = num++;
}
}
}
//sum All Elements by rows: Write your code below
public int sumAllElementsbyRows() {
int sum = 0;
for(int i=0; i<3;i++){
for(int j=0; j<3; j++){
sum += myArray[i][j];
}
}
return sum;
}
//Sum Reversed Diagonal Elements: Write your code below
public int sumAllReversedDiag() {
int sum =0;
for(int i=2; i>=0; i--){
for(int j=2; j>=0; j--){
if(i==j){
sum += myArray[i][j];
}
}
}
return sum;
}
//sum All Elements by columns: Write your code below
public int sumAllElementsbyColumns() {
int sum =0;
for(int j=0; j<3;j++){
for(int i=0; i<3; i++){
sum += myArray[i][j];
}
}
return sum;
}
public static void main(String[] args){
Problem2 myProblem2 = new Problem2();
System.out.println("Sum by rows: " + myProblem2.sumAllElementsbyRows ());
System.out.println("Sum by columns: " + myProblem2.sumAllElementsbyColumns());
System.out.println("Sum reversed diagonal elements: " + myProblem2.sumAllReversedDiag());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.