Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Program to Print an Identity Matrix



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.
Updated on: 2021-03-11T12:35:14+05:30

835 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements