Golang Program To Print 8 Star Pattern


In this tutorial, we will learn how to print 8star pattern using Go programming language.

Syntax

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

Example: Golang Program Code To Print 8 Star Pattern Using A Single Function

Algorithm

  • Step 1 − Import the package fmt.

  • Step 2 − Start the function main ().

  • Step 3 − Declare and initialize the variable.

  • Step 4 − Use of for loop with condition and incrementor.

  • Step 5 − Print the result using fmt.Printf ().

Example

// 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 }

Output

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

Description Of The Code

  • In the above program, we first declare the package main.

  • We imported the fmt package that includes the files of package fmt.

  • Now start the function main () and this function is the entry point of the executable program. It does not take any argument nor return anything.

  • Declare the four integer variable rows and initialize the rows variable to an integer value you want for the number of rows of the 8 star pattern. Here, fmt.Scanln () function is used to read and store the rows value.

  • Using for loop  The condition is given inside an if statement and stop execution is mentioned once the condition is right.

  • And finally printing the result in the form of a diamond shape on the screen using fmt.Printf () function.

Conclusion

We have successfully compiled and executed the Golang program code to print 8 star pattern in the above example.

Updated on: 16-Nov-2022

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements