C Program to Print Diagonal Matrix, Lower and Upper Triangle of Matrix

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

// Program for Diagonal elements  of Matrix
#include<stdio.h>
#include<conio.h>
int main()
{
    int a[50][50],r,c,m,n;
    printf("Enter the values of Rows and Cols");
    scanf("%d %d",&m,&n);
    printf("Enter elements in matrix");
    for(r=0;r<m;r++)
    {
        for(c=0;c<n;c++)
        scanf("%d",&a[r][c]);
    }
    for(r=0;r<m;r++)
    {
        for(c=0;c<n;c++)
        { 
            printf("%5d",a[r][c]);
        }
     printf("\n\n");
    }
    if(m!=n)
     printf("\nInvalid matrix for diagonal elements...");
     else
     {
        printf("\nDiagonal elements are: \n");
         for(r=0;r<m;r++)
      {
           for(c=0;c<n;c++)
        { 
            if(r==c)
            printf("%5d",a[r][c]);
        }
       printf("\n\n");
    }


     }
    return 0;
}

Program 2

// Program for Upper Trangle elements  of Matrix
#include<stdio.h>
#include<conio.h>
int main()
{
    int a[50][50],r,c,m,n;
    printf("Enter the values of Rows and Cols");
    scanf("%d %d",&m,&n);
    printf("Enter elements in matrix");
    for(r=0;r<m;r++)
    {
        for(c=0;c<n;c++)
        scanf("%d",&a[r][c]);
    }
    for(r=0;r<m;r++)
    {
        for(c=0;c<n;c++)
        { 
            printf("%5d",a[r][c]);
        }
     printf("\n\n");
    }
    if(m!=n)
     printf("\nInvalid matrix for diagonal elements...");
     else
     {
        printf("\nLower Triangle elements are: \n");
         for(r=0;r<m;r++)
      {
           for(c=0;c<n;c++)
        { 
            if(r>=c)
            printf("%5d",a[r][c]);
        }
       printf("\n\n");
    }
     printf("\nUpper Triangle elements are: \n");
         for(r=0;r<m;r++)
      {
           for(c=0;c<n;c++)
        { 
            if(r<=c)
            printf("%5d",a[r][c]);
        }
       printf("\n\n");
    }




     }
    return 0;
}

 

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *