Project Number Guessing Game
Context
Section titled “Context”The program picks a random number between 1 and 100. The user must guess it, with hints “too high” or “too low”. The game continues until the user guesses correctly.
This project combines:
- Random generation (
math/rand) - Loops (
for) - Conditionals (
if/else) - User input (
fmt.Scan)
Step‑by‑step code
Section titled “Step‑by‑step code”package main
import ( "fmt" "math/rand" "time")
func main() { // Seed the generator (Go 1.20+ does this automatically, but kept for example) rand.NewSource(time.Now().UnixNano()) secret := rand.Intn(100) + 1 // number between 1 and 100 var guess int attempts := 0
fmt.Println("Guess the number between 1 and 100!")
for { fmt.Print("Your guess: ") _, err := fmt.Scan(&guess) if err != nil { fmt.Println("Invalid input.") continue } attempts++
if guess < secret { fmt.Println("Too low!") } else if guess > secret { fmt.Println("Too high!") } else { fmt.Printf("Congratulations! You found %d in %d attempts.\n", secret, attempts) break } }}Example interaction
Section titled “Example interaction”Guess the number between 1 and 100!Your guess: 50Too low!Your guess: 75Too high!Your guess: 62Too low!Your guess: 68Congratulations! You found 68 in 4 attempts.Possible extensions
Section titled “Possible extensions”- Limit the number of attempts.
- Add option to play again.
- Handle non‑numeric input more robustly.