Java Program to find Sum of Upper Triangle Matrix Including Principal Diagonal Matrix
Program
import java.io.*;
import java.util.*;
public class AddUpperTriangleMatrixPDE {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter the number of rows:");
int row = Integer.parseInt(br.readLine());
System.out.println("Enter the number of columns:");
int col = Integer.parseInt(br.readLine());
int mat[][] = new int[row][col];
System.out.println("Enter " + (row * col) + " values into matrix");
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
mat[i][j] = Integer.parseInt(br.readLine());
System.out.println("Displaying matrix values");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (i <= j)
sum += mat[i][j];
System.out.println("Sum of upper triangle matrix: " + sum);
}
}
Let us understand the program by breaking into simple parts: An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. It extends the abstract class Reader.
The above program prompts the user to enter the number of rows and columns for the matrix. It reads these values from the standard input (keyboard) using BufferedReader
and readLine()
method, and converts them into integers using Integer.parseInt()
. 2D array mat[][] is created to store the matrix data, with dimensions determined by the user-input row and column values. Then the user is again prompted to input values for each cell of the matrix.
Nested for loops are used to take inputs from the user for each cell and save it in the form of array. After each cell value of the matrix is collected, the program uses the nested for loop and prints upper triangular part of the matrix including principal diagonal elements.
For each cell, it checks if the row index i is less than or equal to the column index j
. If so, it calculates the sum by adding it previous cell values stored in sum variable using sum += mat[i][j];
and the Sum of upper triangle matrix including principal diagonal elements is printed.
Output
Enter the number of rows:
3
Enter the number of columns:
3
Enter 9 values into matrix
25
45
78
94
52
81
40
72
35
Displaying matrix values
25 45 78
94 52 81
40 72 35
Sum of upper triangle matrix: 316