Lower Triangular and Upper Triangular Matrix Java

PROGRAM TO PRINT LOWER TRIANGULAR AND UPPER TRIANGULAR MATRIX


import java.util.Scanner;

public class P12 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //M = rows, N = columns
    int M = sc.nextInt();
    int N = sc.nextInt();
    int[][] mat = new int[M][N];
    for(int i=0; i<M; i++)
      for(int j=0; j<N; j++)
        mat[i][j] = sc.nextInt();
      
    for(int i=0; i<M; i++) {
      for(int j=0; j<N; j++) {
        if(i<j)
          System.out.print("0 ");
        else
          System.out.print(mat[i][j]+ " ");
      }
      System.out.println();
    }

    for(int i=0; i<M; i++) {
      for(int j=0; j<N; j++) {
        if(i>j)
          System.out.print("0 ");
        else
          System.out.print(mat[i][j]+ " ");
      }
      System.out.println();
    }
  }
}


OUTPUT
1 0 0 
4 5 0 
7 8 9
1 2 3 
0 5 6 
0 0 9

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java