
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
Golang Program to Print Right Diagonal Matrix
In this article, we will see how to print the right diagonal matrix with the help of suitable examples. A matrix is a 2-d array. Here in the examples, we will use a nested for loop which will iterate through the rows and columns of the matrix to print the right diagonal matrix. The output will be printed on the screen using fmt.println() function which is a print statement in Golang.
Algorithm
Step 1 ? Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.
Step 2 ? Create a function main and in that function create a variable size which refers to the size of matrix.
Step 3 ? Print the size of matrix on the console.
Step 4 ? Run a nested for loop where i variable is used for iterating the outer loop and j variable is used for iterating the inner loop such that i=0 and i<size and j=0 and j<size.
Step 5 ? Create a for nested loop
Step 6 ? Here the position of 1 is used to represent the right diagonal matrix and other non-diagonal elements are filled with 0.
Step 7 ? The square matrix with 0's and 1's is printed on the console using fmt.Println() function where ln refers to new line.
Using Nested For Loop
In this example, we will look how to print the right diagonal matrix using nested for loop. The two variables will be used to iterate through inner and outer loop. Let's understand the example with the help of algorithm and the code.
Example
package main import "fmt" func main() { var size int = 3 //size of matrix fmt.Println("The size of the matrix is:", size) fmt.Println("The matrix with right diagonal matrix is:") for i := 0; i < size; i++ { for j := 0; j < size; j++ { if i+j == size-1 { //if condition satisfies print 1 fmt.Print("1 ") } else { fmt.Print("0 ") //else print 0 } } fmt.Println() //it is used to print new line } }
Output
The size of the matrix is: 3 The matrix with right diagonal matrix is: 0 0 1 0 1 0 1 0 0
Conclusion
We executed the program of printing the right diagonal matrix using an example. The output printed on the console is a square matrix representing the right diagonal matrix. Hence, the program executed successfully.