This Java code takes user input for the size of a 2D array, then prompts the user to input values for the array. It calculates the sum and average of the main diagonal elements by iterating through the array and adding elements where the row and column indexes are equal. It displays the sum and average of the diagonal elements to the user.
R- For some array of size- ROW by COLUMN- compute and display the aver.docx
1. R. For some array of size, ROW by COLUMN, compute and display the average of the left-to-
right diagonal in java
Solution
import java.util.Scanner;
public class SumOfDiagonals {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row,column;
System.out.print("Enter row: ");
row = getInt(sc, "");
System.out.print("Enter column: ");
column = getInt(sc, "");
//Declare 2 Dimensional Arrays
int[][] matrix = new int[row][column];
int sum = 0;
// Input Matrix
System.out.println("Enter matrix ");
for (int i = 0; i < row; i++) {
System.out.println("Enter elements of " + i + " row");
for (int j = 0; j < column; j++) {
matrix[i][j] = getInt(sc, "");
}
}
// Compute Sum of main diagonal elements
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (i == j) {
sum += matrix[i][j];
2. }
}
}
int n;
if(row > column) n = column;
else n = row;
System.out.println("Sum of Diagonal Elements is " + sum);
System.out.println("Average of Diagonal Elements is " + sum/n);
}
public static int getInt(Scanner sc, String prompt) {
int integer = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextInt()) {
integer = sc.nextInt();
isValid = true;
} else {
System.err.println("Error! Invalid number. Try again.");
}
sc.nextLine();
}
return integer;
}
}