Home »
Golang »
Golang Programs
Golang program to create a simple calculator using switch case
Here, we are going to learn how to create a simple calculator using switch case in Golang (Go Language)?
Submitted by Nidhi, on February 20, 2021 [Last updated : March 02, 2023]
How to create a simple calculator using switch case in Golang?
Problem Solution:
In this program, we will create a simple calculator to perform addition, subtraction, multiplication, and division operations using a switch case.
Program/Source Code:
The source code to create a simple calculator using the switch case is given below. The given program is compiled and executed successfully.
Golang code to create a simple calculator using switch case
// Golang program to create a simple calculator
// using switch case.
package main
import "fmt"
func main() {
var num1 int=10
var num2 int=5
var choice int=0
var result int=0
fmt.Println("1: Addition")
fmt.Println("2: Subtraction")
fmt.Println("3: Multiplication")
fmt.Println("4: Division")
fmt.Print("Enter choice: ")
fmt.Scanf("%d",&choice)
switch choice{
case 1:
result=num1+num2
fmt.Printf("Addition is: %d",result)
case 2:
result=num1-num2
fmt.Printf("Subtraction is: %d",result)
case 3:
result=num1*num2
fmt.Printf("Multiplication is: %d",result)
case 4:
result=num1/num2
fmt.Printf("Division is: %d",result)
default:
fmt.Println("Invalid value")
}
}
Output:
RUN 1:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Enter choice: 1
Addition is: 15
RUN 2:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Enter choice: 2
Subtraction is: 5
RUN 3:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Enter choice: 3
Multiplication is: 50
RUN 4:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Enter choice: 4
Division is: 2
RUN 5:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Enter choice: 5
Invalid value
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created four variables num1, num2, choice, result that are initialized with 10, 5, 0, 0 respectively.
Here, we read the choice from the user and execute the particulate case based on entered choice. After that print the result on the console screen.
Golang Switch Statement Programs »