Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Golang Program to Build Right Triangle Using Numbers
In this article, we will write Golang programs to build a right triangle using numbers. The numbers imply that the triangle is composed of numbers. There are many ways to perform this operations, here we have used different examples to provide a better understanding of the concept.
Demonstration
This demonstration explains a right angled triangle representation using numbers. Each row of this triangle is consist of number starting from 1 to the row number. From top the first row has 1, second row has 1, 2 and it goes on.
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
Algorithm
Step 1 ? This program imports the fmt and main package in the program where fmt helps in the formatting of input and output and main helps in generating of executable codes
Step 2 ? In the main function set a variable named rows with some value which indicates no. of rows of the triangle
Step 3 ? Use a nested for loop with i variable in the outer loop and j variable in the inner loop
Step 4 ? In the inner loop print the jth element in every iteration using %d format specifier
Step 5 ? Print new line after every row is printed on the console
Example 1
In this example, right triangle with numbers is printed by using %d format specifier in the nested for loop with i variable in outer loop and j variable in inner loop.
package main
import "fmt"
func main() {
rows := 6
for i := 1; i<= rows; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%d ", j)
}
fmt.Println()
}
}
Output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
Example 2
In this example, we will write a Golang program to build right triangle. The numbers will be printed in pattern by using space with the element.
package main
import "fmt"
func main() {
rows := 6
for i := 1; i<= rows; i++ {
for j := 1; j <= i; j++ {
fmt.Print(j, " ")
}
fmt.Println()
}
}
Output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
Conclusion
We executed and concluded the program of printing left triangle pattern using two examples. In the first example, %d format specifies is used and in the second example, space is used along with the element of the row.
