
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
Print Descending Order Pattern in Golang
In this Go language article, we will write programs to print descending order patterns using a nested for loop as well as using the two nested loops inside the outer loop. Descending order pattern means the higher order elements are placed first and in pattern the rows with highest no. of rows is placed first.
Demonstration
This demonstrates a descending order pattern where every row starts from 1 and decreases by 1 at each column until the end of row. In the top row it has 1-6 numbers and in second row it has 1-5 and it goes on till the 6th row where there is only 1.
1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Algorithm
Step 1 ? Import the fmt and main package in the program where fmt helps in the formatting of the input and output, the main ensures that the program should be an executable program
Step 2 ? Create a main function and in that function set the rows equal to the no of rows you want in the triangle
Step 3 ? Use a nested for loop with I variable used in the outer loop such that i=rows and i>=1 and j used in the inner loop such that j=1 and j<=i
Step 4 ? In every iteration, use inner loop to print the descending order pattern on the console
Step 5 ? Use Println function outside the inner loop so that every row takes a new line
Example1
In this example, two nested for loops will be used to print the desired pattern. In outer loop the i variable will be initialized with no. of rows.
package main import "fmt" func main() { rows := 6 for i := rows; i>= 1; i-- { for j := 1; j <= i; j++ { fmt.Printf("%d ", j) } fmt.Println() } }
Output
1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Example 2
In this example, two nested for loops will be used with one outer for loop where second loop will be used to print space and the third loop will be used to print the elements of the rows.
package main import "fmt" func main() { rows := 6 for i := rows; i>= 1; i-- { for j := 0; j < rows-i; j++ { fmt.Print(" ") } for j := i; j >= 1; j-- { fmt.Printf("%d ", j) } fmt.Println() } }
Output
6 5 4 3 2 1 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
Conclusion
In this article we have looked how we can perform the program of printing the descending order pattern using two examples. In the first example, we used a nested for loop to print the pattern and in the second example, we used two nested loops inside a for loop.