Golang程序 打印8星图案

Golang程序 打印8星图案

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

语法

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

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

算法

  • 第1步 – 导入软件包fmt。

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

  • 第3步 – 声明并初始化变量。

  • 第4步 – 使用带有条件的for循环和增量器。

  • 第5步 – 使用 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() 函数被用来读取和存储行的值。

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

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

总结

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程