Zaenal Arifin

Posted on

# Creating a Calculator with Golang

In this tutorial, we'll guide you through creating a simple calculator using the Go programming language (Golang). Go is a statically typed, compiled language known for its simplicity and efficiency, making it a great choice for various applications, including a calculator.

## Prerequisites

Before we begin, make sure you have the Go programming language installed on your system. You can download it from the official Go website: https://golang.org/

## Step 1: Setting up the Project

Create a new directory for your project and navigate to it using the terminal:

mkdir calculator
cd calculator

## Step 2: Create the Go Source Code

Create a file named main.go and open it in your favorite code editor. This is where we'll write the Go code for our calculator.

package main

import (
"fmt"
"strconv"
)

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

fmt.Println("Simple Calculator in Golang")

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

fmt.Print("Enter operator (+, -, *, /): ")
fmt.Scanln(&operator)

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

result := calculate(num1, num2, operator)

fmt.Printf("Result: %f %s %f = %f\n", num1, operator, num2, result)
}

func calculate(num1, num2 float64, operator string) float64 {
var result float64

switch operator {
case "+":
result = num1 + num2
case "-":
result = num1 - num2
case "*":
result = num1 * num2
case "/":
if num2 != 0 {
result = num1 / num2
} else {
fmt.Println("Error: Division by zero")
}
default:
fmt.Println("Invalid operator")
}

return result
}

## Step 3: Run the Calculator

Now, compile and run the program to use the calculator:

go run main.go

Follow the prompts to enter the numbers and the operator (e.g., +, -, *, /). The calculator will then display the result.

## Conclusion

Congratulations! You've successfully created a simple calculator using Golang. This example demonstrates the basics of user input, functions, and switch statements in Golang. Feel free to expand and improve upon this calculator by adding more features and functionalities.