Q:

Golang program to read and print matrix using the two-dimensional matrix

belongs to collection: Golang Array Programs

0

In this program, we will read elements of the matrix from the user and then print the matrix on the console screen.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to read the print matrix using a two-dimensional matrix is given below. The given program is compiled and executed successfully.

// Golang program to read & print matrix
// using the two-dimensional matrix

package main

import "fmt"

func main() {
	var matrix [2][2]int

	fmt.Printf("Enter matrix elements: \n")
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			fmt.Printf("Elements: matrix[%d][%d]: ", i, j)
			fmt.Scanf("%d", &matrix[i][j])
		}
	}

	fmt.Printf("Matrix elements: \n")
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			fmt.Printf("%d ", matrix[i][j])
		}
		fmt.Printf("\n")
	}
}

Output:

Enter matrix elements:
Elements: matrix[0][0]: 11
Elements: matrix[0][1]: 22
Elements: matrix[1][0]: 33
Elements: matrix[1][1]: 44
Matrix elements:
11 22
33 44

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created 2X2 matrix using two-dimensional array.

    fmt.Printf("Enter matrix elements: \n")
    for i:=0;i<2;i++{
        for j:=0;j<2;j++{
            fmt.Printf("Elements: matrix[%d][%d]: ",i,j)
            fmt.Scanf("%d",&matrix[i][j])
        }
    }

In the above code, we read matrix elements from the user.

    fmt.Printf("Matrix elements: \n")
    for i:=0;i<2;i++{
        for j:=0;j<2;j++{
            fmt.Printf("%d ",matrix[i][j])
        }
        fmt.Printf("\n")
    }

In the above code, we printed the matrix on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to calculate the sum of matrix elem... >>
<< Golang program to insert an item in the array...