Go語言列印正方形星號圖案程式
在本教程中,我們將學習如何使用Go程式語言列印正方形星號圖案。
語法
NESTED FOR LOOP: for [condition | ( init; condition; increment ) | Range] { for [condition | ( init; condition; increment ) | Range] { statement(s); } statement(s); }
示例:使用單個函式列印正方形星號圖案的Go語言程式程式碼
演算法
步驟1 - 匯入fmt包。
步驟2 - 開始函式main()。
步驟3 - 宣告並初始化變數。
步驟4 - 使用帶有條件和增量的for迴圈。
步驟5 - 使用fmt.Println()列印結果。
示例
// GOLANG PROGRAM TO PRINT SQUARE 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 i, j, s int s = 7 // Scanln() function scans the input, reads and stores //the successive space-separated values into successive arguments fmt.Scanln(&s) fmt.Println("GOLANG PROGRAM TO PRINT SQUARE STAR PATTERN") // Use of For Loop // This loop starts when i = 0 // executes till i<s condition is true // post statement is i++ for i = 0; i < s; i++ { for j = 0; j < s; j++ { // print * fmt.Print("* ") } // Ending line after each row fmt.Println() } }
輸出
GOLANG PROGRAM TO PRINT SQUARE STAR PATTERN * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
程式碼描述
在上面的程式中,我們首先宣告main包。
我們匯入了包含fmt包檔案的fmt包。
現在開始函式main(),此函式是可執行程式的入口點。它不接受任何引數也不返回任何值。
宣告三個整型變數i、j和s,並將s變數初始化為您想要的正方形星號圖案的行數的整數值。這裡,使用fmt.Scanln()函式讀取並存儲s值。
使用for迴圈 - 條件在if語句中給出,一旦條件正確,則會提到停止執行。在程式碼的第24行:當i=0時迴圈開始,直到i
最後,使用fmt.Println()函式在螢幕上以星形正方形的形式列印結果。
結論
我們已成功編譯並執行了上述示例中用於列印正方形星號圖案的Go語言程式程式碼。
廣告