Java Program to find the Sum of the Matrix Upper Triangle

Write a Java Program to find the Sum of the Matrix Upper Triangle with an example. We have already explained the steps to display a Matrix Upper triangle in our previous example. 

In this Java Sum of the Matrix Upper Triangle example, we declared an integer matrix. Next, we used for loop to iterate the Matrix. Within the for loop, we find the sum of the Upper triangle of a given matrix.

public class SumOfUpperTriangle {
	
	public static void main(String[] args) {
		
		int i, j, sum = 0;
		
		int[][] Ut_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
		
		for(i = 0; i < 3 ; i++)
		{
			for(j = 0; j < 3; j++)
			{
				if(j > i) {
					sum = sum + Ut_arr[i][j];
				}
			}
		}
		System.out.println("\n The Sum of Upper Triangle Matrix =  " + sum);
	}
}
Java Program to find the Sum of the Matrix Upper Triangle

Java Program to find the Sum of the Matrix Upper Triangle example 2

This Java Upper Triangle Matrix Sum code is the same as the above. However, this Java code allows us to enter the number of rows, columns, and the matrix items.

import java.util.Scanner;

public class SumOfUpperTriangle {
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns, sum = 0;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter UT Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the UT Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr[i][j] = sc.nextInt();
			}		
		}
		
		for(i = 0; i < rows ; i++)
		{
			for(j = 0; j < columns; j++)
			{
				if(j > i) {
					sum = sum + arr[i][j];
				}
			}
		}
		System.out.println("\n The Sum of Upper Triangle Matrix =  " + sum);
	}
}

Output of a Java Matrix Upper Triangle sum

 Please Enter UT Matrix Rows and Columns :  
3 3

 Please Enter the UT Matrix Items :  
10 20 40
80 90 70
11 14 120

 The Sum of Upper Triangle Matrix =  130