Golang Program To Print Square Star Pattern


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

Syntax

NESTED FOR LOOP:
for [condition | ( init; condition; increment ) | Range] {
   for [condition | ( init; condition; increment ) | Range] {
      statement(s);
   }
   statement(s);
}

Example: Golang Program Code To Print Square 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 variables.

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

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

Example

// GOLANG PROGRAM TO PRINT SQUARE 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 i, j, s int s = 7 // Scanln() function scans the input, reads and stores //the successive space-separated values into successive arguments fmt.Scanln(&s) fmt.Println("GOLANG PROGRAM TO PRINT SQUARE STAR PATTERN") // Use of For Loop // This loop starts when i = 0 // executes till i<s condition is true // post statement is i++ for i = 0; i < s; i++ { for j = 0; j < s; j++ { // print * fmt.Print("* ") } // Ending line after each row fmt.Println() } }

Output

GOLANG PROGRAM TO PRINT SQUARE 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 three integer variables i, j and s and initialize the s variable to an integer value you want for the number of rows of the square star pattern. Here, fmt.Scanln () function is used to read and store the s value.

  • Using for loop  The condition is given inside an if statement and stop execution is mentioned once the condition is right. In the line 24 of the code: The loop starts when i = 0 and executes till i<s condition is true and the post statement is i++. In the line 25 of the code: it runs the next loop as for (j=0; j<=i; j++).

  • And finally printing the result in the form of a square with stars shape on the screen using fmt.Println () function.

Conclusion

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

Updated on: 16-Nov-2022

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements