Golang
Golang

 

Introduction

The Go programming language, also known as Golang, is widely used for building fast and efficient software applications. One of the basic and essential programs to get started with any programming language is creating a simple calculator. In this program, we will create a simple calculator that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

Objective

The objective of this program is to implement a simple calculator that can:

  • Add two numbers.
  • Subtract two numbers.
  • Multiply two numbers.
  • Divide two numbers (handling division by zero appropriately).

We will also design the program to allow the user to select an operation and input numbers, and then display the result.

Go Program Code

        package main

        import (
            "fmt"
            "log"
        )

        func main() {
            var num1, num2 float64
            var operation string

            // Welcome message and input prompt
            fmt.Println("Welcome to the Simple Calculator!")
            fmt.Print("Enter the first number: ")
            _, err := fmt.Scanf("%f", &num1)
            if err != nil {
                log.Fatal("Error reading input. Please enter a valid number.")
            }

            fmt.Print("Enter the second number: ")
            _, err = fmt.Scanf("%f", &num2)
            if err != nil {
                log.Fatal("Error reading input. Please enter a valid number.")
            }

            fmt.Print("Enter the operation (+, -, *, /): ")
            _, err = fmt.Scanf("%s", &operation)
            if err != nil {
                log.Fatal("Error reading operation. Please enter a valid operation.")
            }

            // Perform the operation
            var result float64
            switch operation {
            case "+":
                result = num1 + num2
                fmt.Printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result)
            case "-":
                result = num1 - num2
                fmt.Printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result)
            case "*":
                result = num1 * num2
                fmt.Printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result)
            case "/":
                if num2 == 0 {
                    fmt.Println("Error: Division by zero is not allowed.")
                } else {
                    result = num1 / num2
                    fmt.Printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result)
                }
            default:
                fmt.Println("Invalid operation. Please use +, -, *, or /.")
            }
        }

Explanation of the Program Structure

The Go program for the simple calculator follows a structured flow:

  1. Importing Packages: The program imports the necessary packages. We use fmt for user input and output and log for error handling.
  2. Reading Input: The program prompts the user to input two numbers and an arithmetic operator. fmt.Scanf is used to read the user’s input.
  3. Switch Statement: Based on the operator entered by the user, the program uses a switch statement to decide which arithmetic operation to perform. The four operations are handled inside different case blocks.
  4. Error Handling: If the user inputs an invalid number or operation, the program will stop and show an error message using log.Fatal.
  5. Division by Zero: If the user selects division as the operation and the second number is zero, the program will output an error message instead of attempting to divide by zero.
  6. Output: After performing the operation, the result is displayed on the screen using fmt.Printf.

How to Run the Program

To run the simple calculator program written in Go, follow these steps:

    1. Ensure you have the Go programming language installed. You can download it from the official website: Go Downloads.
    2. Create a new file with the extension .go, for example, calculator.go.
    3. Copy and paste the program code above into the newly created file.
    4. Open a terminal/command prompt, navigate to the folder where the calculator.go file is saved, and run the following command to execute the program:
go run calculator.go
  1. The program will prompt you for two numbers and an operation. After entering the inputs, the program will display the result of the chosen operation.

Example Execution:

        Welcome to the Simple Calculator!
        Enter the first number: 15
        Enter the second number: 3
        Enter the operation (+, -, *, /): /
        Result: 15.00 / 3.00 = 5.00
Program created by an AI Assistant. Happy coding!

 

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 :)