Python Program to Print an Identity Matrix

This is a Python Program to read a number n and print an identity matrix of the desired size.

Problem Description

The program takes a number n and prints an identity matrix of the desired size.

Problem Solution

1. Take a value from the user and store it in a variable n.
2. Use two for loop where the value of j ranges between the values of 0 and n-1 and value of i also ranges between 0 and n-1.
3. Print the value of 1 when i is equal to j and 0 otherwise.
4. Exit.

Program/Source Code

Here is the source code of the Python Program to read a number n and print an identity matrix of the desired size. The program output is also shown below.

n=int(input("Enter a number: "))
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()
Program Explanation

1. User must first enter the value and store it in a variable n.
2. The outer for loop enables j to range between 1 and n-1 (as n is not included) while the inner for loop also enables i to range between 1 and n-1.
3. For each iteration, the value of 1 is printed if i is equal to j and value of 0 is printed otherwise.
4. The sep and end parameters of the print function help in formatting and print() allows values to printed in a new line for each iteration of the outer for loop.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a number: 4
1 0 0 0 
0 1 0 0 
0 0 1 0 
0 0 0 1 
 
Case 2:
Enter a number: 5
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

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.