Go語言程式列印X星形圖案
在本教程中,我們將學習如何使用 Go 程式語言列印 X 星形圖案。
語法
for initialization; condition; update { statement(s) }
示例:使用單個函式列印 x 星形圖案的 Go 程式程式碼
演算法
步驟 1 − 匯入 fmt 包和 strconv 包。
步驟 2 − 啟動函式 main ()。
步驟 3 − 宣告並初始化變數。
步驟 4 − 使用帶有條件和增量器的 for 迴圈。
步驟 5 − 使用 fmt.Println ()列印結果。
示例
// GOLANG PROGRAM TO PRINT X STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // start the function main() func main() { fmt.Println("Golang Program to print X star pattern") // Declare the integer variables var i, a, number, row int // initialize the row variable row = 8 // print the X star pattern fmt.Println("X Star Pattern") // Run an outer loop to iterate through rows with // structure for (i=1; i<= number; i++) (where number = row* 2 - 1) number = row*2 - 1 // Use of For Loop // This loop starts when i = 1 // executes till i<=number condition is true // post statement is i++ for i = 1; i <= number; i++ { // Since each row contains exactly row * 2 - 1 columns. // Therefore, run inner loop as for (a=1; a<=number; a++) for a = 1; a <= number; a++ { // For the first diagonal i.e. when row and column number both // are equal, print star whenever if(i == a). // For the second diagonal i.e. stars are printed if(a == number - i + 1) if a == i || a == number-i+1 { fmt.Printf("*") } fmt.Printf(" ") } // PRINT THE RESULT fmt.Println() } }
輸出
Golang Program to print X star pattern X Star Pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
程式碼描述
在上面的程式中,我們首先宣告包 main。
我們匯入了包含 fmt 包檔案的 fmt 包。
現在開始函式 main()。
宣告四個整數變數 i、a、number 和 row。將 row 變數初始化為所需的星形圖案行數的整數值。
使用 for 迴圈 − 條件在 if 語句中給出,並在條件正確時停止執行。
最後使用 fmt.Println將結果列印到螢幕上。
結論
我們在上面的兩個示例中成功編譯並執行了列印 X 星形圖案的 Go 語言程式程式碼。
廣告