Write a program in java to enter numbers in a 2-D array with n rows and m columns and print the sum of the diagonal elements [left and right].
Answers
Answer:
Here is a Java program that uses a nested for loop to enter numbers in a 2-D array with 'n' rows and 'm' columns, and then prints the sum of the diagonal elements (left and right):
import java.util.Scanner;
public class DiagonalSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int n = input.nextInt();
System.out.print("Enter the number of columns: ");
int m = input.nextInt();
int[][] arr = new int[n][m];
int leftDiagonalSum = 0, rightDiagonalSum = 0;
// Entering elements in the array
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print("Enter element for row " + (i + 1) + " column " + (j + 1) + ": ");
arr[i][j] = input.nextInt();
}
}
// calculating left diagonal sum
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(i == j)
leftDiagonalSum += arr[i][j];
}
}
// calculating right diagonal sum
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(i + j == n-1)
rightDiagonalSum += arr[i][j];
}
}
System.out.println("Sum of Left diagonal elements: " + leftDiagonalSum);
System.out.println("Sum of Right diagonal elements: " + rightDiagonalSum);
}
}
This program first prompts the user to enter the number of rows and columns for the 2-D array. Then it uses two nested for loops to enter elements in the array. Inside the nested loops, it checks the condition if the current element is on the left diagonal or right diagonal and adds to the corresponding sum. Finally, it prints the sum of the left diagonal elements and the sum of the right diagonal elements.
When you run the program, it will prompt the user to enter the number of rows and columns and then it will prompt the user to enter the elements of the array, Finally it will show the sum of the left diagonal and right diagonal elements.
You can also use the same logic to calculate the sum of the diagonal elements of a square matrix, where the number of rows and columns are equal.