πŸ“ Exercise : Creating an Interactive Calculator in Go

In this exercise, you will create an interactive calculator in Go that allows the user to input two numbers, select an arithmetic operation ("+", "-", "*", "/"), and print the result. You will practice user input handling, functions, conditional structures, and loops in Go.

Create a Go program that :

1- Implement a getNumber(prompt string) float64 function to handle number input :

Solution :


// getNumber asks the user to enter a number and returns it
func getNumber(prompt string) float64 {
	var input string

	for {
		fmt.Print(prompt)
		fmt.Scan(&input)

		num, err := strconv.ParseFloat(input, 64)

		if err == nil {
			return num
		}

		fmt.Println("Error: Please enter a valid number.")
	}
}
                

2- Implement the getOperator() string Function :

The getOperator function is responsible for retrieving and validating the arithmetic operator from the user. It ensures that only one of the allowed operations (+, -, *, /) is accepted before proceeding with the calculation.

Solution :


// getOperator asks the user for an operation and validates it
func getOperator() string {
	var op string

	for {
		fmt.Print("Choose an operation (+, -, *, /): ")
		fmt.Scan(&op)

		switch op {
		case "+", "-", "*", "/":
			return op
		default:
			fmt.Println("Error: Invalid operation. Try again.")
		}
	}
}
                

3- Implement the calculate(num1 float64, op string, num2 float64) (float64, error) Function

The calculatefunction is responsible for performing the mathematical operation based on the operator provided by the user. It takes two numbers (num1 and num2) and an operator (op), then returns the result along with an error if something goes wrong (like division by zero).

Solution :


// calculate performs the calculation based on the operator
func calculate(num1 float64, op string, num2 float64) (float64, error) {
	switch op {
	case "+":
		return num1 + num2, nil
	case "-":
		return num1 - num2, nil
	case "*":
		return num1 * num2, nil
	case "/":
		if num2 == 0 {
			return 0, fmt.Errorf("Error: Division by zero")
		}
		return num1 / num2, nil
	}

	return 0, fmt.Errorf("Error: Unknown operation")
}
                

4- Implement the main() Function :

The main() function serves as the entry point of the program. Its role is to orchestrate the entire process by calling other functions in a structured way.

Solution :


// main: main loop of the program
func main() {

	fmt.Println("----- Welcome to the Go Calculator -----")

	for {
		// Read user input
		num1 := getNumber("Enter the first number: ")
		operator := getOperator()
		num2 := getNumber("Enter the second number: ")

		// Perform the calculation
		result, err := calculate(num1, operator, num2)

		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Printf("Result: %.2f %s %.2f = %.2f\n", num1, operator, num2, result)
		}

		// Ask if the user wants to continue
		var response string
		fmt.Print("Do you want to perform another calculation? (yes/no): ")
		fmt.Scan(&response)

		if response != "yes" {
			fmt.Println("Thank you for using the calculator! See you soon.")
			break
		}
	}
}
                

Final Code :


package main

import (
	"fmt"
	"strconv"
)

// getNumber asks the user to enter a number and returns it
func getNumber(prompt string) float64 {
	var input string

	for {
		fmt.Print(prompt)
		fmt.Scan(&input)

		num, err := strconv.ParseFloat(input, 64)

		if err == nil {
			return num
		}

		fmt.Println("Error: Please enter a valid number.")
	}
}

// getOperator asks the user for an operation and validates it
func getOperator() string {
	var op string

	for {
		fmt.Print("Choose an operation (+, -, *, /): ")
		fmt.Scan(&op)

		switch op {
		case "+", "-", "*", "/":
			return op
		default:
			fmt.Println("Error: Invalid operation. Try again.")
		}
	}
}

// calculate performs the calculation based on the operator
func calculate(num1 float64, op string, num2 float64) (float64, error) {
	switch op {
	case "+":
		return num1 + num2, nil
	case "-":
		return num1 - num2, nil
	case "*":
		return num1 * num2, nil
	case "/":
		if num2 == 0 {
			return 0, fmt.Errorf("Error: Division by zero")
		}
		return num1 / num2, nil
	}

	return 0, fmt.Errorf("Error: Unknown operation")
}

// main: main loop of the program
func main() {

	fmt.Println("----- Welcome to the Go Calculator -----")

	for {
		// Read user input
		num1 := getNumber("Enter the first number: ")
		operator := getOperator()
		num2 := getNumber("Enter the second number: ")

		// Perform the calculation
		result, err := calculate(num1, operator, num2)

		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Printf("Result: %.2f %s %.2f = %.2f\n", num1, operator, num2, result)
		}

		// Ask if the user wants to continue
		var response string
		fmt.Print("Do you want to perform another calculation? (yes/no): ")
		fmt.Scan(&response)

		if response != "yes" {
			fmt.Println("Thank you for using the calculator! See you soon.")
			break
		}
	}
}

                

Congratulations! πŸŽ‰ By completing this exercise, you have built a fully functional interactive calculator in Go, while applying key programming principles like functions, loops, error handling, and user input validation. This project is a solid foundation for more complex Go applications. πŸš€

πŸš€ Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! β˜•πŸ˜Š

πŸ’» I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! πŸ™Œ


β˜• Buy me a coffee