JAVA PROGRAM TO DISPLAY UPPER TRIANGULAR MATRIX

Upper Triangular Matrix in java 2D Array.


This program display Upper Triangular Matrix in java 2D Array.
In this program we enter the values into matrix and we are going to print the above diagonal and lower diagonal elements zero.





import java.util.*;
public class PrintUpperTriangularMatrix
{
    public static void main(String args[])
    {
        int m, n, i, j;
        int a[][]=new int[10][10];
        Scanner sc=new Scanner (System. In);
        System.out.println("Enter the order of a square matrix :");
        m=sc.nextInt();
        n=sc.nextInt();
        /* checking order of matrix and then if true then enter the values
         * into the matrix a[][]
        */
        if(m == n)
        {
            System.out.println("Enter elements in the matrix:"+m*n);
            for(i=0; i<m; i++)
            {
                for(j=0; j<n; j++)
                a[i][j]=sc.nextInt();
            }
        }
       // Display the entered value
        System.out.println ("You have entered the following matrix");
       for (i=0; i<m; i++)
       {
           for (j=0; j<n; j++)
           System.out.print (a[i][j] + " ");
           System.out.println ();
        }
        // Display the Upper Triangular Matrix
        System.out.println("Upper triangular matrix  the given matrix is:");
        for(i=0; i<m; i++)
        {
            for(j=0; j<n; j++)
            {
                if(i>j)
                a[i][j] = 0;
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }       
}



Sample Output
Enter the order of a square matrix:
4
4
Enter elements in the matrix: 16
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
You have entered the following matrix
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
Upper triangular matrix the given matrix is:
1 2 3 4
0 6 7 8
0 0 2 3
0 0 0 7



Variable Description


Sl. No.
Variable Name
Data Type
Purpose
1
main()
static void
Main function
2
a[][]
int
To store the values in an 2D array
3
i , j
int
For running the loop
4
m, n

For order of the matrix
4
sc
Scanner
To instantiate the Scanner class which exists in java.util.* package

Similar Java Program

Addition of two matrices in Java






SHARE THIS
Previous Post
Next Post