Golang
Golang






Go Programming: Countdown Timer

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 using time.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

  1. Ensure you have Go installed on your system. You can download it from
    Go’s official website.
  2. Save the code in a file named countdown_timer.go.
  3. Open a terminal and navigate to the directory containing the file.
  4. Run the program with the following command:

    go run countdown_timer.go
  5. Enter the desired countdown duration in seconds and watch the countdown in real time.

Happy Coding! If you have questions, feel free to reach out at support@learnprogramming.com.

Copyright © Learn Programming. All rights reserved.



By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)