This blog is under construction

Saturday 29 June 2013

C program to print upper and lower triangle of a matrix

Write a C program to print the upper triangular and lower triangular matrix.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int **data, i, j, n;

        /* Enter the order of the input matrix */
        printf("Enter the order of matrix:\n");
        scanf("%d", &n);

        /* dynamically allocate memory to store matrix elements */
        data = (int **)malloc(sizeof (int) * n);
        for (i = 0; i < n; i++)
                data[i] = (int *)malloc(sizeof (int) * n);

        /* get the inputs from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++)
                for (j = 0; j < n; j++)
                        scanf("%d", &data[i][j]);

        /* print the upper triangular matrix */
        printf("Upper triangular matrix:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++)
                        if (j >= i)
                                printf("%3d", data[i][j]);
                        else
                                printf("%3d", 0);
                printf("\n");
        }

        /* print the lower triangular matrix */
        printf("Lower triangular matrix:\n");
        for (i  = 0; i < n; i++) {
                for (j = 0; j < n; j++)
                        if (j <= i)
                                printf("%3d", data[i][j]);
                        else
                                printf("%3d", 0);
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the order of matrix:
  3

  Enter your inputs:
  10  20  30
  40  50  60
  70  80  90

  Upper triangular matrix:
   10 20 30
    0 50 60
    0  0 90

  Lower triangular matrix:
   10  0  0
   40 50  0
   70 80 90



No comments:

Post a Comment