C program to create identity matrix or unit matrix

Definition of Identity matrix – A square matrix in which every non-diagonal element is zero and every diagonal element is one, is called a unit matrix or an identity matrix

Make a program in the C programming language to create or print an identity matrix or unit matrix of order n. Below is the C program —

/* C program to create an identity matrix of n x n order */
#include<stdio.h>
#include<conio.h>
void main()
{
     int ar1[100][100],n,i,j;
     
     printf("Enter value of n to create an identity matrix of order n ");
     scanf("%d",&n);
     
     printf(" Identity matrix is - \n");
     for(i=0;i<n;i++)
     {
           for(j=0;j<n;j++)
           {
                 if(i==j)
                 {
                         ar1[i][j]=1;
                         printf("%d ",ar1[i][j]);
                 }
                 else
                 {
                     ar1[i][j]=0;
                     printf("%d ",ar1[i][j]);
                 }
           }
           printf("\n");
     }
     getch();
}

yashan has written 70 articles

4 thoughts on “C program to create identity matrix or unit matrix

  1. syed khizer says:

    to check whether it is identity or not?
    can u pls tell what is wrong
    #include
    main()
    {
    int a[2][2],i,j,flag;
    printf(“\n the matrix:”);
    for(i=0;i<2;i++)
    {for(j=0;j<2;j++)
    {
    scanf("%3d",&a[i][j]);
    }
    }
    printf("the matrix is:\n");
    for(i=0;i<2;i++)
    {
    for(j=0;j<2;j++)
    {
    if(i==j)
    {

    a[i][j]!=0;
    flag=1;}
    else
    {
    a[i][j]!=1;
    flag=2;}
    }
    }
    if(flag==1&&flag==2)
    {
    printf("yes");}
    else
    {
    printf("n"); }
    }

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>