PHP Program to print the identity matrix

It is a beginner level PHP program to print a matrix with the help of loops. To understand this example we should have knowledge of the following topics

What is an identity matrix?

The identity matrix is a square matrix of any order in which the diagonal(when the index of row and column are the same) elements are all 1, and all other elements in the matrix must be 0.

For example, 

1 0 0

0 1 0

0 0 1

In the above matrix, we can see that all the diagonal values are 1 and others are 0 so we can say that this is an identity matrix.

How to print an identity matrix using PHP?

To print the identity matrix first we have to accept the order of the matrix into the variable rc from the user to store the number of rows and columns. After that print the identity matrix using nested for loop , with the condition 'i < rc' and the condition 'j < rc' becomes false, check the value 'i == j' where comes the diagonal element,  if that true then print 1 otherwise print 0

ALGORITHM

Step 1: Accept the values into the variable rc from the user to store the number of rows and columns

Step 2: To print the identity matrix using the for loop first assign the value 0 into the variable i and perform the sub-step until the condition 'i < row' becomes false and increment the value of variable i in every iteration

  • Assign the value 0 into the variable j and perform the sub-step until the condition 'j < col' becomes false and increment the value of variable j in every iteration
    • Check condition 'i == j' if true then print 1 otherwise print 0

PHP Source Code

                                          <?php
$rc = readline("Enter the number of rows and columns: \n");
echo "The identity matrix of order ",$rc," is: \n";
for ($i = 0; $i < $rc; $i++) {
    for ($j = 0; $j < $rc; $j++) {
        if ($i == $j) {
            echo "1 ";
        } else {
            echo "0 ";
        }
    }
    echo "\n";
}
?>
                                      

OUTPUT

Enter the number of rows and columns:  5
The identity matrix of order 5 is:
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