Go語言程式列印映象上三角星形圖案


在本教程中,我們將學習如何使用 Go 程式語言列印下三角形圖案。

語法

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

在程式碼中,我們使用 for 迴圈重複執行程式碼塊,直到滿足指定的條件。

示例:使用單個函式列印下三角形星形圖案的 Go 語言程式

演算法

  • 步驟 1 − 匯入 fmt 包。

  • 步驟 2 − 開始 main() 函式。

  • 步驟 3 − 宣告並初始化變數。

  • 步驟 4 − 使用帶條件和增量的 for 迴圈。

  • 步驟 5 − 開始 main() 函式。

  • 步驟 6 − 呼叫 upper() 函式列印映象上三角星形圖案。

  • 步驟 7 − 使用 fmt.Println() 列印結果。

示例

// GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN package main // fmt package provides the function to print anything import "fmt" // Create a function upper () func upper(row int) bool { //i for rows and j for columns //row denotes the number of rows you want to print var i int var j int row = 6 fmt.Scanln(&row) //Outer loop work for rows for i = 0; i < row; i++ { //inner loop work for space for j = row - i; j > 1; j-- { //prints space between two stars fmt.Print(" ") } //inner loop for columns for j = 0; j <= i; j++ { //prints star fmt.Print("* ") } //throws the cursor in a new line after printing each line fmt.Println() // print the result } // Outer loop fo Rows for i = 1; i <= row; i++ { // Inner loop 1 to print triangle 3 for j = 1; j < i; j++ { // Printing whitespace fmt.Print(" ") } // Inner loop 2 to print triangle 4 for j = i; j <= row; j++ { // Printing star and whitespace fmt.Print("*" + " ") } // By now done with one row so new line fmt.Println() } return true } // start the function main () func main() { fmt.Println("GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN") fmt.Print(upper(6)) // print the result }

輸出

GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN
     * 
    * * 
   * * * 
  * * * * 
 * * * * * 
* * * * * * 
* * * * * * 
 * * * * * 
  * * * * 
   * * * 
    * * 
     * 
true

程式碼描述

  • 在上面的程式中,我們首先宣告 main 包。

  • 我們匯入了 fmt 包,其中包含 fmt 包的檔案。

  • 接下來,我們建立 upper() 函式來列印圖案。

  • 宣告三個整數變數 i、j 和 row。將 row 變數初始化為映象上三角星形圖案的行數的整數值。

  • 使用 for 迴圈  條件在 if 語句中給出,並在條件正確時停止執行。

  • 開始 main() 函式。

  • 接下來,我們呼叫 upper() 函式來列印圖案。

  • 最後使用 fmt.Println() 在螢幕上列印結果。

結論

在上面的示例中,我們已成功編譯並執行了 Go 語言程式程式碼,以列印映象上三角星形圖案。

更新於: 2022-11-16

218 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.