Golang 打印反向金字塔星型图案
在这个教程中,我们将编写一个Go语言程序来打印反向金字塔星型图案。我们将展示如何打印出反向金字塔星型图案。
*********
*******
*****
***
*
如何打印倒金字塔星型图案
上面是一个图案,可以清楚地看到每一行星号的数量在递减。如果总行数是5,那么图案会是这样的:第一行有9个星号,第二行有7个星号,第三行有5个星号,以此类推。
我们将使用4个循环来打印这个图案。
用Golang打印倒金字塔星型图案的程序
语法
for [condition | ( init; condition; increment) | Range] {
statement(s);
}
步骤
- 步骤1 - 导入fmt包
-
步骤2 - 开始main()函数
-
步骤3 - 声明并初始化整数变量,(row = 要打印的行数)
-
步骤4 - 使用不同的循环以打印反向金字塔星型图案
-
步骤5 - 在打印完一行的所有列之后,移动到下一行,即打印新行
示例
//GOLANG PROGRAM TO PRINT REVERSE PYRAMID STAR PATTERN
package main
// fmt package provides the function to print anything
import "fmt"
//this is the main function
func main() {
//initialize the number of rows to print
var rows = 5
//declaring variables with integer datatype
fmt.Println("\nThis is the Reverse pyramid pattern")
var i, j int
//displaying the pattern
for i = rows; i >= 1; i-- {
//printing the spaces
for space := 1; space <= rows-i; space++ {
fmt.Print(" ")
}
//printing the stars
for j = i; j <= 2*i-1; j++ {
fmt.Printf("*")
}
for j = 0; j < i-1; j++ {
fmt.Printf("*")
}
fmt.Println("")
}
}
输出
This is the pyramid pattern
*********
*******
*****
***
*
代码描述
-
在上面的程序中,我们首先声明了主要的包。
-
我们导入了包含fmt包文件的fmt包。
-
现在开始定义主函数main()
-
接下来声明整数变量,我们将用它们来打印正确的金字塔星型模式。
-
我们使用不同的循环来打印空格和星号,以打印反向金字塔星型模式。
-
在每行模式之后换行。
-
最后使用fmt.Printf()将结果打印到屏幕上。
结论
在上面的示例中,我们成功解释并执行了用于打印反向金字塔星型模式的Golang程序代码。