Print unit matrix using Array in C


This program is a C program that creates an identity matrix. The identity matrix is a square matrix with all the elements in the diagonal as 1 and the rest of the elements as 0. The program takes the number of rows and columns as input from the user and stores it in the variables 'r' and 'c' respectively. It then uses nested loops to iterate through the rows and columns of the matrix.

Inside the nested loops, the program checks if the current row and column are equal (i.e, the current element is in the diagonal) and sets the value at that position to 1. If the current row and column are not equal (i.e, the current element is not in the diagonal), the program sets the value at that position to 0. The program then prints the matrix. The overall purpose of this code is to generate an identity matrix of the given size.

Source Code

#include<stdio.h>
int main()
{
  int i,j,r,c,a[10][10];
  printf("\nEnter the Row Limit:");
  scanf("%d",&r);
  printf("\nEnter the Column Limit:");
  scanf("%d",&c);
  for(i=0;i<r;i++)
  {
    for(j=0;j<c;j++)
    {
       if(i==j)
       {
         a[i][j]=1;
       }
       else
       {
         a[i][j]=0;
       }
    }
    printf("\n");
  }
  for(i=0;i<r;i++)
  {
    for(j=0;j<c;j++)
    {
      printf("\t%d",a[i][j]);
    }
    printf("\n");
  }
  return 0;
}
To download raw file Click Here

Output

Enter the Row Limit:3
Enter the Column Limit:3
1  0  0
0  1  0
0  0  1


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