Golang Program to print a hollow star triangle pattern


In this tutorial, we will learn how to print hollow star triangle pattern using Go programming language.

The user can specify the maximum number of rows to print as an inverted pyramid star pattern using this GO programmed. Here, we'll print the inverted Pyramid of * symbols up till the user-specified rows are reached.

Algorithm

STEP 1 − Import the package fmt

STEP 2 − Start function main()

STEP 3 − Declare and initialize the variables and assign value to them.

STEP 4 − Initialize a variable to store the number of rows that star pattern should print.

STEP 5 − Use two for loops to iterate over the triangle pattern where each iteration of the loop adds 1 from the value of i which ranges between 0 and row - 1.

STEP 6 − Print both the results with the empty spaces and the character "*" by using function fmt.Println().

Example

In this program we will write a go language program to print a hollow star triangle pattern using an external user defined function.

package main
import "fmt"
func main() {
   var i, j, row int

   // the hollow triangle that we wish to print will have 9 rows
   row = 9
   fmt.Println("Hollow Right Angled Triangle Star Pattern")

   // implementing the logic through loops
   for i = 1; i <= row; i++ {
      for j = 1; j <= i; j++ {
         if i == 1 || i == row || j == 1 || j == i {
            fmt.Printf("*")
         } else {
            fmt.Printf(" ")
         }
      }
      fmt.Println()
   }
}

Output

Hollow Right Angled Triangle Star Pattern
*
**
* *
*  *
*   *
*    *
*     *
*      *
*********

Explanation

We have created a go language program to print a hollow star pattern. In this program we have used two for loops along with if conditions in the main() section of the program.

Conclusion

We have successfully compiled and executed a go language code to print a hollow star triangle pattern. We have created the above program by using the loops and if conditionals.

Updated on: 10-Feb-2023

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements