How to print Identity matrix of given size in C++

In this tutorial, we will learn how to print an identity matrix of nth size in C++ with an example, algorithm, and a program.

An identity matrix is a square matrix with all the principal diagonal elements having value one and the rest of the elements having zero.

Printing an identity matrix in C++ program means the user just have to enter the size of the square matrix and the program will generate the identity matrix of entered size.

Algorithm to print identity matrix of a given size

  1. declare a variable to store the size of the matrix and make input.
  2. start an outer loop from i = 0 to n,
  3. start an inner loop inside an outer loop from j = 0 to n.
  4. if i is equal to j, then print 1 else print 0.

Also learn: Rotation of a square matrix by 90 degrees in C++

C++ program to print the identity matrix of a given size

#include<iostream>
using namespace std;

int main(){
    int n; //to store size of matrix

    //taking input in variable n
    printf("Enter the size: ");
    cin>>n;

    cout<<"\nIdentity matrix of size "<<n<<": \n";
    
    //priting square matrix
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(i == j)
                cout<<"1 ";
            else
                cout<<"0 ";
        }
        cout<<endl;  //changing to next row
    }
    return 0;
}

Output: 

Enter the size: 5

Identity matrix of size 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

Time complexity: O(n^2) where n is the length of row and column of the identity matrix

You may also read: 

  1. How to swap both diagonals of a matrix in C++
  2. How to check the given matrix is magic square or not in C++

Leave a Reply

Your email address will not be published. Required fields are marked *