Golang程序 打印镜面上星三角图案

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

代码描述

  • 在上面的程序中,我们首先声明包main。

  • 我们导入了fmt包,其中包括包fmt的文件。

  • 接下来,我们创建函数 upper() 来打印图案。

  • 声明三个整数变量i、j和row。将row变量初始化为你想要的镜像上星三角图案的行数的整数值。

  • 使用for循环 - 在if语句内给出条件,一旦条件正确就提到停止执行。

  • 启动 函数main()。

  • 接下来,我们调用函数 upper() 来打印图案。

  • 最后使用 fmt.Println() 在屏幕上打印结果 。

总结

我们已经成功地编译并执行了Golang程序代码,以打印上述例子中的镜像上星三角图案。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程