Golang Program to Print Pyramid Star Pattern


In this tutorial we will write a Go language code to print pyramid star pattern. We will depict how you can print the pyramid star pattern.

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

How to print a Pyramid star pattern?

A pattern is shown above, and in the pattern, you can clearly see that 2 stars is increasing with increase in each row. The pattern goes like this 1 star in first row, 3 stars in second row, 5 starts in 3rd row and goes on.

We will use 3 for loops to print this pattern.

Example: Golang program to print pyramid star pattern

Syntax

For loop as a while loop in GO language:
for condition {

   // code to be executed
   // increment or decrement the count variable.
}

Algorithm

  • STEP 1 − Import the package fmt

  • STEP 2 − Start the function main()

  • STEP 3 − Declare and initialize the integer variables, (row= number rows to print)

  • STEP 4 − The first for loop iterate through the row from 1 to “row”.

  • STEP 5 − The second for loop iterate through columns from 1 to row-1, to print a star pattern.

  • STEP 6 − The third for loop iterates from 0 to (2*i-1), and print star.

  • STEP 7 − After printing all columns of a row move to next line i.e., print new line.

Example

//GOLANG PROGRAM TO PRINT A PYRAMID STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // calling the main function func main() { //declaring variables with integer datatype var i, j, k, row int // initializing row variable to a value to store number of rows row = 5 //print the pattern fmt.Println("\nThis is the pyramid pattern") //displaying the pattern for i = 1; i <= row; i++ { //printing the spaces for j = 1; j <= row-i; j++ { fmt.Print(" ") } //printing the stars for k = 0; k != (2*i - 1); k++ { fmt.Print("*") } // printing a new line fmt.Println() } }

Output

This is the pyramid pattern
      *
     ***
    *****
   *******
  *********

Description of the Code

  • In the above program, we first declare the package main.

  • We imported the fmt package that includes the files of package fmt.

  • Now start the function main()

  • Next declare the integer variables that we are going to use in order to print the right pyramid star pattern in go code.

  • In this code the first for loop, iterates from 0 to the end of the row

  • The second for loop iterates from 1 to row-1, and prints empty spaces.

  • The third for loop iterates from 0 to (2*i-1), and prints the (*) star character.

  • Then we need to break the line after each row gets printed.

  • And finally printing the result on the screen using fmt.Printf().

Conclusion

In the above examples we have successfully compiled and executed the Golang program code to print the pyramid star pattern.

Updated on: 22-Nov-2022

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements