Golang 打印8星图案

Golang 打印8星图案

在本教程中,我们将学习如何使用Go编程语言打印8星图案。

语法

for initialization; condition; update {
   statement(s)
}

示例:使用单个函数打印8个星号图案的Golang程序代码

步骤

  • 第一步 − 导入 fmt 包。

  • 第二步 − 开始函数 main()

  • 第三步 − 声明并初始化变量。

  • 第四步 − 使用 for 循环与条件和增量器。

  • 第五步 − 使用 fmt.Printf() 打印结果。

示例

// GOLANG PROGRAM TO PRINT 8 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 variable
   var rows int
   rows = 8

   // Scanln() function scans the input, reads and stores
   //the successive space-separated values into successive arguments
   fmt.Scanf("%d", &rows)
   fmt.Printf("GOLANG PROGRAM TO PRINT 8 STAR PATTERN\n")

   // Use of For Loop
   // This loop starts when i <= rows*2-1 GOLANG PROGRAM TO PRINT 8 STAR PATTERN
   // executes till j<=rows condition is satisfied
   // post statement is j++
   i := 1
   for i <= rows*2-1 {
      if i == 1 || i == rows || i == rows*2-1 {
         j := 1
         for j <= rows {
            if j == 1 || j == rows {
               fmt.Printf(" ")
            } else {
               fmt.Printf("*")
            }
            j++
         }
      } else {
         // This loop starts when k <= rows
         // executes till one of the conditions satisfies k==1 / k == rows
         // post statement is k++
         k := 1
         for k <= rows {
            if k == 1 || k == rows {
               fmt.Printf("*")
            } else {
               fmt.Printf(" ")
            }
            k++
         }
      }
      fmt.Printf("\n")
      i++
   }
   // print the result using fmt.Printf () function
}

输出

GOLANG PROGRAM TO PRINT 8 STAR PATTERN
******
*    *
*    *
*    *
*    *
*    *
*    *
******
*    *
*    *
*    *
*    *
*    *
*    *
******

代码描述

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

  • 我们导入了包含fmt包文件的fmt包。

  • 现在开始函数 main() ,这个函数是可执行程序的入口点。它不接受任何参数,也不返回任何内容。

  • 声明四个整数变量rows,并将rows变量初始化为所需的8星图的行数。这里使用 fmt.Scanln() 函数来读取和存储rows的值。

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

  • 最后使用 fmt.Printf() 函数以菱形形式在屏幕上打印结果。

结论

我们已成功编译并执行了上述示例中打印8星图案的Golang程序代码。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程