Write a Java program that gets a 4x4 array of numbers and that calculates the sum and average of numbers on the main diagonal, ie the diagonal that goes from the left corner down to the right corner. Examples of resulting programs are:
Enter a 4x4 matrix row by row:
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7
The sum of numbers in the diagonal is: 16
The average of numbers in the diagonal is: 4
Write a program that: - Prints appropriate prompt to user. - Loading a 4x4 matrix. - Calculates sum and average for the main diagonal - Prints the result with an appropriate user prompt.
Hint: Store the matrix in a 4x4 double array.
Ans
code:-
import java.util.*;
class MyClass {
public static void main(String[ ] args) {
//create object for taking input
Scanner sc = new Scanner(System.in);
//creating double array of 4 by 4
double a[][]=new double[4][4];
double sum=0.0;//initialise sum
//prompt
System.out.println("Enter matrix elements of size 4x4");
//loading matrix a
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
a[i][j]=sc.nextDouble();
if(i==j){//sum the elements on diagonal
sum=sum+a[i][j];
}
}
}//display the sum
System.out.println("The sum of numbers in the diagonal is: "+sum);
//display the average
System.out.println("The average of numbers in the diagonal is: "+(sum/4.0));
}
}
code with output:-
.
...
..
If any doubt ask in the comments.
Get Answers For Free
Most questions answered within 1 hours.