Step 1 Create a new project . Name it Assignment_1_2 . Step 2 Build a solution .
ID: 3787342 • Letter: S
Question
Step 1 Create a new project.
Name it Assignment_1_2 .
Step 2 Build a solution.
Write the Java source code necessary to build a solution for the problem below:
Write a Java program to create a 4-by-4 matrix with the following values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, and 16. Your program must read from the matrix and display the sum of the elements in the matrix. The program must then display the sum of each row, each column, and the diagonal elements of the matrix.
Step 3 Compile and execute your code.
Explanation / Answer
public class Assignment_1_2
{
public static void main (String[] args)
{
int[][] matrix = new int[][]{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
//initialize all sums to 0
int rowsum = 0;
int colsum = 0;
int diagonalsum = 0;
for(int row=0;row<4;row++)
{
rowsum = 0;
for(int col=0;col<4;col++)
{
rowsum = rowsum + matrix[row][col]; //sum of elements of 4 rows,columnwise
}
System.out.println("Sum of elements of row"+ row +" = "+rowsum);
}
for(int col=0;col<4;col++)
{
colsum = 0;
for(int row=0;row<4;row++)
{
colsum = colsum + matrix[row][col]; //sum of elements of 4 columns rowwise
}
System.out.println("Sum of elements of column"+ col +" = "+colsum);
}
for(int row=0;row<4;row++)
{
for(int col=0;col<4;col++)
{
if(row == col) // row=col for diagonal elements
diagonalsum = diagonalsum + matrix[row][col];
}
}
System.out.println("Sum of diagnonal elements = "+diagonalsum);
}
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.