Golang Program To Print Downward Triangle Star Pattern


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

Syntax

for initialization; condition; update {
   statement(s)
}

In the code, we use the for loop to repeat a block of code until the specified condition is met.

Example: Golang Program To Print Download Triangle Star Pattern Using One Single Function

Algorithm

  • Step 1 − Import the package fmt.

  • Step 2 − Start the function main ().

  • Step 3 − Declare and initialize the variables.

  • Step 4 − Use of for loop with condition and incrementor.

  • Step 5 − Print the result using fmt.Println ().

Example

// GOLANG PROGRAM TO PRINT DOWNWARD TRIANGLE STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // start the function main () func main() { // Declare and initialize the integer variables var i int var j int var row int = 9 // Calling Scanln () function for // scanning and reading the input // int given in standard input fmt.Scanln(&row) fmt.Println("**** Golang program to print Downward Triangle Star Pattern ****") // using for loop to iterate through rows for i = row - 1; i >= 0; i-- { // using for loop to iterate through columns for j = 0; j <= i; j++ { // prints star fmt.Printf("* ") } //throws the cursor in a new line after printing each line fmt.Println() } }

Output

**** Golang program to print Downward Triangle Star 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 () and this function is the entry point of the executable programs. It does not take any argument nor return anything.

Declare the three integer variables i, j and row. Initialize the row variable to an integer value you want for the number of rows of the downward triangle star pattern. And call the Scanln () function for scanning and reading the input.

Using for loop  The condition is given inside an if statement and stop execution is mentioned once the condition is right.

And last printing the result on the screen using fmt.Println.

Conclusion

We have successfully compiled and executed the Golang program code to print the downward triangle star pattern in the above example.

Updated on: 16-Nov-2022

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements