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语言程序代码。
广告