Sling Academy
Home/Golang/Building a Simple Calculator with Go's Control Flow

Building a Simple Calculator with Go's Control Flow

Last updated: November 23, 2024

Control flow is an essential concept in programming, allowing developers to dictate the order in which instructions are executed. In Go, control flow statements such as if, switch, and loops are used to control the execution of code. In this article, we will build a simple calculator application in Go, focusing on using these control flow statements to handle various arithmetic operations selected by the user.

Basic Calculator with If-Else

Let's start with a basic example, where we'll build a simple calculator using the if-else statement to determine which operation the user wants to perform. The user will be able to select two numbers and a basic arithmetic operation: addition, subtraction, multiplication, or division.


package main

import (
    "fmt"
)

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

    fmt.Println("Enter first number:")
    fmt.Scanln(&num1)

    fmt.Println("Enter second number:")
    fmt.Scanln(&num2)

    fmt.Println("Enter operation (+, -, *, /):")
    fmt.Scanln(&operation)

    if operation == "+" {
        fmt.Printf("Result: %.2f\n", num1+num2)
    } else if operation == "-" {
        fmt.Printf("Result: %.2f\n", num1-num2)
    } else if operation == "*" {
        fmt.Printf("Result: %.2f\n", num1*num2)
    } else if operation == "/" {
        if num2 != 0 {
            fmt.Printf("Result: %.2f\n", num1/num2)
        } else {
            fmt.Println("Error: Division by zero")
        }
    } else {
        fmt.Println("Invalid operation")
    }
}

Using Switch for Control Flow

While if-else is a good starting point, a switch statement can make the code cleaner and more readable. Let's refactor our calculator to use a switch case for operation selection.


package main

import (
    "fmt"
)

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

    fmt.Println("Enter first number:")
    fmt.Scanln(&num1)

    fmt.Println("Enter second number:")
    fmt.Scanln(&num2)

    fmt.Println("Enter operation (+, -, *, /):")
    fmt.Scanln(&operation)

    switch operation {
    case "+":
        fmt.Printf("Result: %.2f\n", num1+num2)
    case "-":
        fmt.Printf("Result: %.2f\n", num1-num2)
    case "*":
        fmt.Printf("Result: %.2f\n", num1*num2)
    case "/":
        if num2 != 0 {
            fmt.Printf("Result: %.2f\n", num1/num2)
        } else {
            fmt.Println("Error: Division by zero")
        }
    default:
        fmt.Println("Invalid operation")
    }
}

Advanced Calculator with Error Handling

To further improve the calculator, let's add some error handling. This version of the calculator will check for invalid input types using fmt.Scan's returned errors and protect against invalid operations. We'll wrap our code in a loop to allow continuous user operations until a specific exit command is given.


package main

import (
    "fmt"
    "os"
)

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

        fmt.Println("Enter first number (or type 'exit' to quit):")
        if _, err := fmt.Scanln(&num1); err != nil {
            if err.Error() == "unexpected newline" {
                os.Exit(0)
            } else {
                fmt.Println("Invalid input. Please enter a number.")
                fmt.Scanln()
                continue
            }
        }

        fmt.Println("Enter second number:")
        fmt.Scanln(&num2)

        fmt.Println("Enter operation (+, -, *, /):")
        fmt.Scanln(&operation)

        switch operation {
        case "+":
            fmt.Printf("Result: %.2f\n", num1+num2)
        case "-":
            fmt.Printf("Result: %.2f\n", num1-num2)
        case "*":
            fmt.Printf("Result: %.2f\n", num1*num2)
        case "/":
            if num2 != 0 {
                fmt.Printf("Result: %.2f\n", num1/num2)
            } else {
                fmt.Println("Error: Division by zero")
            }
        default:
            fmt.Println("Invalid operation")
        }
    }
}

In this improved version, you can see that we've added a loop and incorporated error handling to manage unexpected inputs. This enhanced user experience showcases how control flow in Go can be utilized to manage logic and errors effectively.

Next Article: Go - Iterating Collections: Using Range for Real-World Examples

Previous Article: Ways to check type of a variable in Go

Series: Variables & Control Flow

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant