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
*
***
*****
*******
*********
***********
*************
***************
*************
***********
*********
*******
*****
***
*
代码描述
-
在上面的程序中,我们首先声明包main。
-
我们导入了fmt包,其中包括包fmt的文件。
-
现在启动函数 main() ,这个函数是可执行程序的入口。它不接受任何参数,也不返回任何东西。
-
声明四个整数变量x、y、z和rows。将rows变量初始化为你想要的钻石星形图案的行数的整数值。这里, fmt.Scanln() 函数被用来读取和存储rows的值。
-
使用for循环 – 条件是在if语句中给出的,一旦条件正确就停止执行。在代码中,当x := rows -1 ,y := 1和i = 1时,for循环开始。
-
最后用 fmt.Println() 函数在屏幕上打印出钻石形状的结果,该函数对其操作数使用默认格式并写入标准输出。
总结
我们已经成功地编译并执行了Golang程序代码来打印上述例子中的钻石星形图案。
极客教程