
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements