⚡ TL;DR
Print the number pyramid pattern in Go. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Number Pyramid pattern is a classic loop exercise. Here’s the complete implementation in Go with working code and output.
Pattern to Print
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5Implementation
package main
import ("fmt"; "strings"; "strconv")
func main() {
n := 5
for i := 1; i <= n; i++ { fmt.Println(strings.Repeat(" ", n-i) + strings.Repeat(strconv.Itoa(i)+" ", i)) }
}Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5How It Works
Row i repeats the digit i exactly i times, centered with leading spaces.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
Related Patterns
- Number Pyramid in Python
- Number Pyramid in Dart
- Number Pyramid in Swift
- Number Triangle in Go
- Increasing Number Triangle in Go
- Decreasing Number Triangle in Go
FAQ
How do you print the Number Pyramid pattern in Go?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Go implementation with expected output is shown in the sections above.
What is the time complexity of the Number Pyramid pattern in Go?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
