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.