Solved programming problem

Printing Identity matrix in C.

Source code

#include<stdio.h>

int main()

{

    int n,r,c;

    int array[100][100];

    printf("Please Enter a value for n X n Identity matrix: ");

    scanf("%d",&n);

    for(r=0; r<n; r++)

    {

        for(c=0; c<n; c++)

        {

            if(r!=c)

            {

                array[r][c]=0;  ///saving the value as 0

            }

            else if(r==c)

            {

                array[r][c]=1;  ///if the row and column are same then save the value as 1.

            }

        }

    }

    printf("
Your %d X %d Id Identity matrix is: 
",n,n);

    for(r=0; r<n; r++)

    {

        for(c=0; c<n; c++)

        {

            printf("%d ",array[r][c]);

        }printf("
");

    }

    return 0;

}

Output

Please Enter a value for n X n Identity matrix:

Your 5 x 5 Id Identity matrix is:

1 0 0 0 0

0 1 0 0 0

0 0 1 0 0

0 0 0 1 0

0 0 0 0 1

 

Join the discussion

Add your comment