To print a Diamond Pattern in Go, we use nested loops. The outer loop controls the rows and the inner loops control the spaces and stars (*) to form the pattern.
In this example,
printDiamond
that takes the desired number of rows n
as a parameter.for
loops, where the outer loop runs from 1 to n
and the inner loops control the spaces and stars in each row.package main
import (
"fmt"
"strings"
)
func printDiamond(n int) {
for i := 1; i <= n; i++ {
spaces := strings.Repeat(" ", n-i)
stars := strings.Repeat("*", 2*i-1)
fmt.Println(spaces + stars)
}
for i := n - 1; i >= 1; i-- {
spaces := strings.Repeat(" ", n-i)
stars := strings.Repeat("*", 2*i-1)
fmt.Println(spaces + stars)
}
}
// Example usage
func main() {
printDiamond(5)
}
* *** ***** ******* ********* ******* ***** *** *
In this tutorial, we learned How to print Diamond Pattern in Go language with well detailed examples.