Go語言列印倒三角星形圖案程式


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

語法

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

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

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

演算法

  • 步驟1 − 匯入fmt包。

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

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

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

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

示例

// 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() } }

輸出

**** Golang program to print Downward Triangle Star Pattern ****
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

程式碼描述

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

我們匯入了包含fmt包檔案的fmt包。

現在開始函式main(),此函式是可執行程式的入口點。它不接受任何引數也不返回任何值。

宣告三個整型變數i、j和row。將row變數初始化為您想要倒三角星形圖案的行數的整數值。並呼叫Scanln()函式進行掃描和讀取輸入。

使用for迴圈  條件在if語句中給出,一旦條件正確,則會停止執行。

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

結論

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

更新於:2022年11月16日

瀏覽量:210

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.