Check and print unit matrix using Array in C


The program is a C program that checks if a given matrix is a Unit matrix or not. A unit matrix is a square matrix in which all the elements of the main diagonal are 1 and all other elements are 0. The program first takes the number of rows and columns of the matrix as input from the user. Then it takes the values of the matrix as input from the user, element by element.

Then the program uses two nested for loops to traverse through the elements of the matrix and checks if the element is present on the main diagonal (i.e. i==j) and if it is 1. If it is, it increments the variable 'one' by 1. If the element is not on the main diagonal and is 0, it increments the variable 'zero' by 1.

After the loops have finished executing, the program checks if the total number of elements in the matrix (r*c) is equal to the number of 1's on the main diagonal and the number of zeroes present in the matrix (one+zero). If it is, the program prints that it is a Unit matrix. Else, it prints that it is not a Unit matrix. Finally, the program returns 0 to indicate successful execution.

Source Code

#include<stdio.h>
int main()
{
  int a[10][10],i,j,one=0,zero=0,r,c;
  printf("\nEnter No of Rows:");
  scanf("%d",&r);
  printf("\nEnter No of Columns:");
  scanf("%d",&c);
  printf("\nEnter the Matrix Values:");
  for(i=0;i<r;i++)
  {
    for(j=0;j<c;j++)
    {
      scanf("\n%d",&a[i][j]);
    }
  }
  for(i=0;i<r;i++)
  {
    for(j=0;j<c;j++)
    {
      if(i==j)
      {
        if(a[i][j]==1)
        {
           one++;
        }
      }
      else
      {
        if(a[i][j]==0)
        {
           zero++;
        }
      }
    }
  }
  if((r*c)==(one+zero))
  {
    printf("%d*%d Unit matrix",r,c);
  }
  else
  {
    printf("%d*%d Not Unit matrix",r,c);
  }
  return 0;
}
  
To download raw file Click Here

Output

Enter No of Rows:3
Enter No of Columns:3
Enter the Matrix Values:1
0
0
0
1
0
0
0
1
3*3 Unit Matrix


List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C