This blog is under construction

Wednesday 24 July 2013

C program to print upper triangular matrix

Write a C program to print upper triangular matrix.


  #include <stdio.h>
  #define MAXROWS 10
  #define MAXCOLS 10

  int main() {
        int i, j, n;
        int upper[MAXROWS][MAXCOLS];

        /* get the order of the matrix from the user */
        printf("Enter the number of n:");
        scanf("%d", &n);

        /* Boundary Check */
        if (n > MAXROWS || n < 0) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* get the entries for the input matrix */
        printf("\nEnter the matrix entries:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &upper[i][j]);
                }
        }

        /* printing for upper triangular matrix */
        printf("\n\nUpper triangular matrix for the given input:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        if (j < i) {
                                printf("0  ");
                        } else {
                                printf("%d  ", upper[i][j]);
                        }
                }
                printf("\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of n:3
  Enter the matrix entries:
  1  2  3
  4  5  6
  7  8  9

  Upper triangular matrix for the given input:
  1  2  3  
  0  5  6  
  0  0  9  


No comments:

Post a Comment