Golang Program to Print Reverse Pyramid Star Pattern


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

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

How to print a Reverse Pyramid star pattern?

A pattern is shown above, and in the pattern, you can clearly see that 2 stars is decreasing with increase in each row. If the total rows are 5, the pattern goes like these 9 stars in first row, 7 stars in second row, 5 starts in 3rd row and goes on decreasing.

We will use 4 for loops to print this pattern.

Golang program to print reverse pyramid star pattern

Syntax

for [condition | ( init; condition; increment) | Range] {
   statement(s);
}

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 − Use different for loops in order to print the reverse pyramid star pattern.

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

Example

//GOLANG PROGRAM TO PRINT REVERSE PYRAMID STAR PATTERN package main // fmt package provides the function to print anything import "fmt"
//this is the main function func main() { //initialize the number of rows to print var rows = 5 //declaring variables with integer datatype fmt.Println("\nThis is the Reverse pyramid pattern") var i, j int //displaying the pattern for i = rows; i >= 1; i-- { //printing the spaces for space := 1; space <= rows-i; space++ { fmt.Print(" ") } //printing the stars for j = i; j <= 2*i-1; j++ { fmt.Printf("*") } for j = 0; j < i-1; j++ { fmt.Printf("*") } 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.

  • We have used different for loops, to print spaces and stars in order to print the reverse pyramid star pattern.

  • Break the line after each row pattern.

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

Conclusion

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

Updated on: 22-Nov-2022

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements