Go語言列印菱形星號圖案程式


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

語法

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

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

演算法

  • 步驟1 − 匯入fmt包。

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

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

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

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

示例

// GOLANG PROGRAM TO PRINT DIAMOND 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 variables var x, y, z, rows int // initialize the rows variable rows = 8 fmt.Scanln(&rows) fmt.Println("GOLANG PROGRAM TO PRINT DIAMOND STAR PATTERN") // Use of For Loop for the upper half for x = 1; x <= rows; x++ { // This loop starts when y = 1 // executes till y<=rows condition is true // post statement is y++ for y = 1; y <= rows-x; y++ { fmt.Printf(" ") } for z = 1; z <= x*2-1; z++ { fmt.Printf("*") } fmt.Println() } // Use of For Loop for the lower half for x = rows - 1; x > 0; x-- { // This loop starts when y = 1 // executes till y<=rows condition is true // post statement is y++ for y = 1; y <= rows-x; y++ { fmt.Printf(" ") } for z = 1; z <= x*2-1; z++ { fmt.Printf("*") } fmt.Println() // print the result using fmt.Println () function } }

輸出

GOLANG PROGRAM TO PRINT DIAMOND STAR PATTERN
       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************
 *************
  ***********
   *********
    *******
     *****
      ***
       *

程式碼描述

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

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

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

  • 宣告四個整型變數x、y、z和rows。將rows變數初始化為您想要菱形星號圖案的行數的整數值。這裡,fmt.Scanln ()函式用於讀取並存儲rows值。

  • 使用for迴圈 − 條件在if語句中給出,並在條件正確時提及停止執行。在程式碼中,當x := rows – 1,y := 1和i = 1時,for迴圈開始。

  • 最後,使用fmt.Println ()函式以菱形形狀在螢幕上列印結果,該函式使用其運算元的預設格式進行格式化並寫入標準輸出。

結論

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

更新於:2022年11月16日

453 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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