Introduction
A countdown timer is a useful tool for various scenarios such as tracking time during an activity or setting reminders.
This program demonstrates how to create a countdown timer in Go that counts down from a given number of seconds to zero.
Objective
The objective of this project is to create a simple console-based countdown timer that takes input in seconds and displays the countdown in real time.
This helps learners understand Go’s time-related functions and loops.
Code
package main
import (
"fmt"
"time"
)
func main() {
var seconds int
fmt.Println("Welcome to the Countdown Timer!")
fmt.Print("Enter the number of seconds for the countdown: ")
fmt.Scanln(&seconds)
if seconds <= 0 {
fmt.Println("Please enter a positive number of seconds.")
return
}
fmt.Println("Countdown starts now:")
for i := seconds; i > 0; i-- {
fmt.Printf("%d seconds remaining...\n", i)
time.Sleep(1 * time.Second)
}
fmt.Println("Time's up!")
}
Explanation
The program structure is as follows:
- User Input: The program prompts the user to enter the number of seconds for the countdown.
- Validation: The input is validated to ensure it’s a positive number.
-
Countdown Loop: A
for
loop iterates from the given number down to 1, printing the remaining seconds and pausing for 1 second between iterations usingtime.Sleep
. - Completion Message: Once the countdown reaches zero, the program prints “Time’s up!” to indicate the end of the countdown.
How to Run the Program
-
Ensure you have Go installed on your system. You can download it from
Go’s official website. -
Save the code in a file named
countdown_timer.go
. - Open a terminal and navigate to the directory containing the file.
-
Run the program with the following command:
go run countdown_timer.go
- Enter the desired countdown duration in seconds and watch the countdown in real time.