Header Ads

Python Program to Print an Identity Matrix

Python Program to Print an Identity Matrix
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()


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






Powered by Blogger.