Go語言程式列印8角星圖案


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

語法

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

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

演算法

  • 步驟 1 − 匯入 fmt 包。

  • 步驟 2 − 啟動函式 main ()

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

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

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

示例

// GOLANG PROGRAM TO PRINT 8 STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // start the function main () // this function is the entry point of the executable program func main() { // Declare the integer variable var rows int rows = 8 // Scanln() function scans the input, reads and stores //the successive space-separated values into successive arguments fmt.Scanf("%d", &rows) fmt.Printf("GOLANG PROGRAM TO PRINT 8 STAR PATTERN\n") // Use of For Loop // This loop starts when i <= rows*2-1 GOLANG PROGRAM TO PRINT 8 STAR PATTERN // executes till j<=rows condition is satisfied // post statement is j++ i := 1 for i <= rows*2-1 { if i == 1 || i == rows || i == rows*2-1 { j := 1 for j <= rows { if j == 1 || j == rows { fmt.Printf(" ") } else { fmt.Printf("*") } j++ } } else { // This loop starts when k <= rows // executes till one of the conditions satisfies k==1 / k == rows // post statement is k++ k := 1 for k <= rows { if k == 1 || k == rows { fmt.Printf("*") } else { fmt.Printf(" ") } k++ } } fmt.Printf("\n") i++ } // print the result using fmt.Printf () function }

輸出

GOLANG PROGRAM TO PRINT 8 STAR PATTERN
******
*    *
*    *
*    *
*    *
*    *
*    *
******
*    *
*    *
*    *
*    *
*    *
*    *
******

程式碼描述

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

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

  • 現在啟動函式 main (),此函式是可執行程式的入口點。它不接受任何引數也不返回任何內容。

  • 宣告四個整數變數 rows 並將 rows 變數初始化為 8 角星圖案行數所需的整數值。這裡, fmt.Scanln () 函式用於讀取和儲存 rows 值。

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

  • 最後使用 fmt.Printf () 函式在螢幕上以菱形形狀列印結果。

結論

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

更新於: 2022-11-16

261 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.