Golang Program to Print an Identity Matrix

Go ProgrammingServer Side ProgrammingProgramming

The steps to print an identity matrix using Golang is as follows :

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

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

Example

 Live Demo

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter a number: ")
   fmt.Scanf("%d", &n)
   for i:=0; i<n; i++{
      for j:=0; j<n; j++{
         if i == j{
            fmt.Print("1 ")
         } else {
            fmt.Printf("0 ")
         }
      }
      fmt.Println()
   }
}

Output

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
raja
Published on 31-Jul-2021 15:06:42
Advertisements