Golang Program To Print X Star Pattern


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

Syntax

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

Example: Go Program Code to Print x Star Pattern Using a Single Function

Algorithm

  • Step 1 − Import the package fmt and strconv package.

  • Step 2 − Start 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 X STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // start the function main() func main() { fmt.Println("Golang Program to print X star pattern") // Declare the integer variables var i, a, number, row int // initialize the row variable row = 8 // print the X star pattern fmt.Println("X Star Pattern") // Run an outer loop to iterate through rows with // structure for (i=1; i<= number; i++) (where number = row* 2 - 1) number = row*2 - 1 // Use of For Loop // This loop starts when i = 1 // executes till i<=number condition is true // post statement is i++ for i = 1; i <= number; i++ { // Since each row contains exactly row * 2 - 1 columns. // Therefore, run inner loop as for (a=1; a<=number; a++) for a = 1; a <= number; a++ { // For the first diagonal i.e. when row and column number both // are equal, print star whenever if(i == a). // For the second diagonal i.e. stars are printed if(a == number - i + 1) if a == i || a == number-i+1 { fmt.Printf("*") } fmt.Printf(" ") } // PRINT THE RESULT fmt.Println() } }

Output

Golang Program to print X star pattern
X 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().

  • Declare the four integer variables i, a, number and row. Initialize the row variable to an integer value you want for the number of rows of the star pattern.

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

  • And last printing the result on the screen using fmt.Println.

Conclusion

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

Updated on: 16-Nov-2022

617 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements