Python Program to Print an Identity Matrix

PythonServer Side ProgrammingProgramming

When it is required to print an identity matrix, nested loops can be used.

Below is a demonstration for the same −

Example

 Live Demo

n = 4
print("The value of n has been initialized to " +str(n))
for i in range(0,n):
   for j in range(0,n):
      if(i==j):
         print("1",sep=" ",end=" ")
      else:
         print("0",sep=" ",end=" ")
   print()

Output

The value of n has been initialized to 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Explanation

  • The value of ‘n’ is initialized.
  • A ‘for’ loop runs from 0 to ‘n’.
  • Another nested ‘for’ loop runs from 0 to ‘n’ again.
  • If the variables in the first and second ‘for’ loop are equal, then ‘1’ is printed.
  • Otherwise, if they are not equal, then ‘0’ is printed on the console.
raja
Published on 11-Mar-2021 12:34:44
Advertisements