Golang 打印菱形星星图案
在本教程中,我们将学习如何使用Go编程语言打印菱形星星图案。
语法
for initialization; condition; update {
statement(s)
}
示例: 使用单个函数打印钻石星型的Golang程序代码
步骤
- 步骤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
*
***
*****
*******
*********
***********
*************
***************
*************
***********
*********
*******
*****
***
*
代码描述
-
在上面的程序中,我们首先声明了主包。
-
我们导入了包含fmt包文件的fmt包。
-
现在开始函数 main() 这个函数是可执行程序的入口点。它不需要任何参数,也不返回任何内容。
-
声明四个整数变量x、y、z和rows。将rows变量初始化为你想要的菱形星型图的行数。这里使用 fmt.Scanln() 函数来读取和存储行数的值。
-
使用for循环 - 条件是在if语句中给出的,一旦条件满足就停止执行。在代码中,for循环在x := rows – 1,y := 1和i = 1时开始。
-
最后使用 fmt.Println() 函数将结果以菱形形状打印在屏幕上,该函数使用默认格式对其操作数进行格式化并写入标准输出。
结论
我们已经成功编译并执行了Go语言程序代码,用于在上面的示例中打印菱形星型图案。