Go Program to Print Numbers 1 to n
for loop like this: for i := 1; i <= n; i++ { fmt.Println(i) } where n is the limit.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { var n int fmt.Print("Enter a number: ") fmt.Scan(&n) for i := 1; i <= n; i++ { fmt.Println(i) } }
Dry Run
Let's trace printing numbers from 1 to 3 through the code
Input
User enters n = 3
Initialize counter
Set i = 1
Check condition
Is i (1) <= n (3)? Yes, proceed
Print number
Print 1
Increment counter
i becomes 2
Repeat check
Is i (2) <= n (3)? Yes, proceed
Print number
Print 2
Increment counter
i becomes 3
Repeat check
Is i (3) <= n (3)? Yes, proceed
Print number
Print 3
Increment counter
i becomes 4
Final check
Is i (4) <= n (3)? No, stop loop
| i |
|---|
| 1 |
| 2 |
| 3 |
Why This Works
Step 1: Input reading
The program reads the number n from the user to know how many numbers to print.
Step 2: Loop setup
A for loop starts from 1 and runs until it reaches n, controlling how many numbers to print.
Step 3: Printing numbers
Inside the loop, each number i is printed on its own line using fmt.Println(i).
Alternative Approaches
package main import "fmt" func printNumbers(i, n int) { if i > n { return } fmt.Println(i) printNumbers(i+1, n) } func main() { var n int fmt.Print("Enter a number: ") fmt.Scan(&n) printNumbers(1, n) }
package main import "fmt" func main() { var n int fmt.Print("Enter a number: ") fmt.Scan(&n) i := 1 for i <= n { fmt.Println(i) i++ } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so it executes n times, making the time complexity O(n).
Space Complexity
The program uses a fixed amount of extra memory regardless of n, so space complexity is O(1).
Which Approach is Fastest?
The simple for loop is fastest and most memory efficient compared to recursion, which uses extra stack space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(1) | Simple and efficient printing |
| Recursion | O(n) | O(n) | Elegant but uses more memory |
| While-like for loop | O(n) | O(1) | Alternative loop style preference |