Golang程序 打印金字塔星形图案

Golang程序 打印金字塔星形图案

在本教程中,我们将编写一个Go语言代码来打印金字塔星形图案。我们将描述如何打印金字塔星形图案。

       *
     * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

如何打印一个金字塔星形图案

上面显示了一个图案,在图案中,你可以清楚地看到2颗星是随着每行的增加而增加的。这个图案是这样的:第一行是1颗星,第二行是3颗星,第三行开始是5颗星,一直到最后。

我们将使用3个for循环来打印这个图案。

例子。打印金字塔星形图案的Golang程序

语法

For loop as a while loop in GO language:
for condition {

   // code to be executed
   // increment or decrement the count variable.
}

算法

  • 第1步 – 导入软件包 fmt

  • 第2步 – 启动函数main()

  • 第3步 – 声明并初始化整数变量,(row=要打印的行数)

  • 第4步 – 第一个for循环遍历从1到 “row “的行。

  • 第5步 – 第二个for循环从1到 “row-1 “遍历各列,打印一个星形图案。

  • 第6步 – 第三个for循环从0到(2*i-1)迭代,并打印星形图案。

  • 第7步 – 打印完一行的所有列后,移到下一行,即打印新的一行。

例子

//GOLANG PROGRAM TO PRINT A PYRAMID STAR PATTERN
package main

// fmt package provides the function to print anything
import "fmt"

// calling the main function
func main() {

   //declaring variables with integer datatype
   var i, j, k, row int

   // initializing row variable to a value to store number of rows
   row = 5

   //print the pattern
   fmt.Println("\nThis is the pyramid pattern")

   //displaying the pattern
   for i = 1; i <= row; i++ {

      //printing the spaces
      for j = 1; j <= row-i; j++ {
         fmt.Print(" ")
      }

      //printing the stars
      for k = 0; k != (2*i - 1); k++ {
         fmt.Print("*")
      }

      // printing a new line
      fmt.Println()
   }
}

输出

This is the pyramid pattern
      *
     ***
    *****
   *******
  *********

代码的描述

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

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

  • 现在启动函数main()

  • 接下来声明我们要使用的整数变量,以便在go代码中打印右金字塔星形图案。

  • 在这段代码中,第一个for循环,从0到行的末尾进行迭代。

  • 第二个for循环从1迭代到第1行,并打印出空位。

  • 第三个for循环从0迭代到(2i-1),并打印出()星字符。

  • 然后,我们需要在每一行被打印后断行。

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

结论

在上面的例子中,我们已经成功地编译并执行了Golang程序代码来打印金字塔星形图案。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程