Golang 打印镜像上方星形三角形图案
在本教程中,我们将学习如何使用Go编程语言打印向下的三角形图案。
语法
for initialization; condition; update {
statement(s)
}
在代码中,我们使用for循环来重复执行一个代码块,直到满足指定的条件。
例如:使用一个单独的函数来打印下载三角星图案的Golang程序
步骤
- 步骤1 − 导入fmt包。
-
步骤2 − 开始函数 main() 。
-
步骤3 − 声明并初始化变量。
-
步骤4 − 使用带有条件和递增器的for循环。
-
步骤5 − 开始函数 main() 。
-
步骤6 − 调用函数 upper() 以打印镜像上三角星图案。
-
步骤7 − 使用 fmt.Println() 打印结果。
示例
// GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN
package main
// fmt package provides the function to print anything
import "fmt"
// Create a function upper ()
func upper(row int) bool {
//i for rows and j for columns
//row denotes the number of rows you want to print
var i int
var j int
row = 6
fmt.Scanln(&row)
//Outer loop work for rows
for i = 0; i < row; i++ {
//inner loop work for space
for j = row - i; j > 1; j-- {
//prints space between two stars
fmt.Print(" ")
}
//inner loop for columns
for j = 0; j <= i; j++ {
//prints star
fmt.Print("* ")
}
//throws the cursor in a new line after printing each line
fmt.Println() // print the result
}
// Outer loop fo Rows
for i = 1; i <= row; i++ {
// Inner loop 1 to print triangle 3
for j = 1; j < i; j++ {
// Printing whitespace
fmt.Print(" ")
}
// Inner loop 2 to print triangle 4
for j = i; j <= row; j++ {
// Printing star and whitespace
fmt.Print("*" + " ")
}
// By now done with one row so new line
fmt.Println()
}
return true
}
// start the function main ()
func main() {
fmt.Println("GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN")
fmt.Print(upper(6))
// print the result
}
输出
GOLANG PROGRAM TO PRINT MIRROR UPPER STAR TRIANGLE PATTERN
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
true
代码描述
-
在上面的程序中,我们首先声明了包。
-
我们导入了包,该包含有包的文件。
-
接下来,我们创建了函数 upper() 来打印模式。
-
声明了三个整数变量i、j和row。将row变量初始化为所需的镜像上三角星型图案的行数。
-
使用for循环 - 条件在if语句内给出,并且在条件满足时停止执行。
-
开始 main()函数 。
-
接下来,我们调用函数 upper() 来打印模式。
-
最后使用 fmt.Println() 在屏幕上打印结果。
结论
我们成功编译并执行了上面示例中打印镜像上三角星型图案的Golang程序代码。