Golang Program To Print Upper Star Triangle Pattern


In this tutorial, we will write a program to print an upper star triangle pattern in go language. In an upper star triangle pattern, there can be only one star printed in the first row and the base must be at the bottom.

Printing Upper Star Triangle Pattern In Go Programming Language

Algorithm

Step 1 − Import the fmt package.

Step 2 − Start the main function.

Step 3 − In the next step, we need to initialize the integer variables viz i, j, k, and rows. The row variable contains a number of rows to be printed in the star pattern

Step 4 − We will be using three for loops to implement the logic for printing this star pattern.

Step 5 − Use the first for loop from i = 0 to rows and increment the value of i in each step.

Step 6 − Then within this for loop use the second for loop to iterate from row variable to i and decrement the value of j in each step.

Step 7 − This for loop will be used to print the spaces after which the “*” will be printed.

Step 8 − Now start the third for loop from k = 0 to i and increment this variable in each step. Print the * symbol using fmt.Println() function.

Step 9 − Repeat these steps till i becomes equal to a number of rows and the required pattern will be printed.

Example

package main
import "fmt"
func main() {
   var rows int = 9
   fmt.Println("Upper star triangle pattern")
   fmt.Println()
   for i := 1; i <= rows; i++ {
      for j := 1; j < i; j++ {
         fmt.Printf(" ")
      }
      for k := i; k <= rows; k++ {
         fmt.Printf("*")
      }
      fmt.Println()
   }
}

Output

Upper star triangle pattern

*********
 ********
  *******
   ******
    *****
     ****
      ***
       **
        *

Conclusion

We have successfully compiled and executed a go language program to print an upper star triangle pattern.

Updated on: 02-Jan-2023

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements