Java Program to find Sum of Upper Triangle Matrix Excluding Principal Diagonal Matrix

This Java program adds values of upper triangle matrix. The program considers only upper triangle excluding principal diagonal elements of the matrix.

Program

import java.io.*;
import java.util.*;
public class AddUpperTriangleMatrix
{
	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 excluding principal diagonal elements.

For each cell, it checks if the row index i is lesser than 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 excluding principal diagonal elements of the matrix is printed.

Output

Enter the number of rows:
3
Enter the number of columns:
3
Enter 9 values into matrix
15
68
41
30
99
12
8
77
56
Displaying matrix values
15	68	41	
30	99	12	
8	77	56	
Sum of upper triangle matrix: 121

Tags: