How to Write Calculator Program using Switch Case in Swift


A Calculator is an electronic device which is used to perform different types of mathematical operations like subtraction, addition, division, multiplication, etc. We can also create a calculator using Switch case and simple arithmetic operations in Swift programming. It will also perform the same mathematical operations as the original calculator.

Example Demonstration

Enter any two numbers:
Number 1: 
43
Number 2: 
234

SIMPLE CALCULATOR
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Percentage
Choose (1/2/3/4/5):
2

Result = -191.0

Here, we first enter the numbers on which we want to perform the operation. Then we select the operation from the given list and then it will display the result after performing the specified operation on the given numbers.

In Swift, we can write calculator programs using the following methods:

  • Using switch case

  • Using function with switch case

Algorithm

Step 1 − Read two or more numbers from the user using the readLine() function.

Step 2 − Display the choices(such as addition, subtraction, multiplication, division and percentage) to the user.

Step 3 − Read any one choice from the user using the readLine() function.

Step 4 − Use the switch case statement to move to the selected operation.

Step 5 − Display the final result.

Method 1: Calculator Program using Switch Case

In this method, we simply create a calculator program which will perform division, addition, multiplication, subtraction, and percentage using switch case statements. Where the user can enter the values and can able to perform any mathematical operation from the given list.

Example

In the following Swift program, we are going to create a simple calculator program using switch case statements. So first we will read two numbers from the user on which we will perform the mathematical operation using the readLine() function and store them in two separate variables. After that, we will display a list of mathematical operations to the user from where he/she will select the required operation. After that, we will pass the selection to the switch statement and execute the associated case block. If the input choice is not available, then it will execute the default block of the switch statement.

import Foundation
import Glibc

print("SIMPLE CALCULATOR")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Percentage")
print("Enter the name of any one operation:")
let selection = readLine()

print("Now enters any two numbers on which you want to perform the operation:")
print("Number 1: ")
let num1 = Double(readLine()!)!

print("Number 2: ")
let num2 = Double(readLine()!)!

var result : Double = 0.0

// Switch statement to create a calculator
switch(selection){
    case "Addition":
    result = Double(num1 + num2)
    print("Result =", result)
    
    case "Subtraction":
    result = Double(num1 - num2)
    print("Result =", result)
    
    case "Multiplication":
    result = Double(num1 * num2)
    print("Result =", result)
    
    case "Division":
    if (num2 != 0){
        result = Double(num1 / num2)
        print("Result =", result)
    }else{
        print("Division with zero is not possible")
    }
    
    case "Percentage":
    if (num2 != 0){
        result = Double((num1 / num2) * 100)
        print("Result =", result)
    }else{
        print("Invalid values")
    }
    
    default:
    print("Invalid selection")
}

Output

SIMPLE CALCULATOR
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Percentage
Enter the name of any one operation:
Addition
Now enters any two numbers on which you want to perform the operation:
Number 1: 
5
Number 2: 
10
Result = 15.0

Method 2: Calculator program using Function with Switch Case

In this method, we will create separate functions to perform tasks like Addition(), Subtraction(), Multiplication(), Division(), etc. Then we will use a switch case statement to select the function according to the user's choice.

Example

In the following Swift program, we will create a calculator using the function with Switch Case. So first we create five functions for basic calculator operations like add, subtract, multiply, divide, and percentage. Then we take two numbers from the user using the readLine() function. After that, we provide a list of operations to the user so that he/she can select any one option. Then the control flows into the switch case statement to check for the specified choice. If the given choice is found, execute that block of code and display the output by calling the given function. Otherwise, execute the default block and display "Invalid selection! Try Again!”.

import Foundation
import Glibc

func Addition(_ x: Double, _ y: Double) -> Double{
    return x + y
}

func Subtraction(_ x: Double, _ y: Double) -> Double{
    return x - y
}

func Multiplication(_ x: Double, _ y: Double) -> Double{
    return x * y
}
func Division(_ x: Double, _ y: Double) -> Double{
    if (y != 0){
        return x/y
    }else{
        print("Cannot divide by zero") 
        return 0
    }
}

func Percentage(_ x: Double, _ y: Double) -> Double{
    if (y != 0){
        return ((x / y) * 100)
    }else{
        print("Cannot divide by zero") 
        return 0
    }
}

print("Enter any two numbers:")
print("Number 1: ")
let num1 = Double(readLine()!)!

print("Number 2: ")
let num2 = Double(readLine()!)!

print("SIMPLE CALCULATOR")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Percentage")
print("Choose (1/2/3/4/5):")
let selection = readLine()

var result : Double = 0.0

// Switch statement to create calculator
switch(selection){
    case "1":
    result = Addition(num1, num2)
    print("Result =", result)
    
    case "2":
    result = Subtraction(num1, num2)
    print("Result =", result)
    
    case "3":
    result = Multiplication(num1, num2)
    print("Result =", result)
    
    case "4":
    result = Division(num1, num2)
    print("Result =", result)
    
    case "5":
    result = Percentage(num1, num2)
    print("Result =", result)
    
    default:
    print("Invalid selection! Try Again!")
}

Output

Enter any two numbers:
Number 1: 
20
Number 2: 
5
SIMPLE CALCULATOR
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Percentage
Choose (1/2/3/4/5):
4
Result = 4.0

Real−Life Usage

The real−life usage of the calculator program is:

  • The calculator program is commonly used education system to help students to understand and practice how arithmetic operations work.

  • It is also used in the finance industry to calculate loan payments, interest rates, investment returns, etc.

  • It is also used by engineers for designing and analysing systems, processes, etc.

  • It is also used in construction to calculate the quantity of material, construction cost, etc.

Conclusion

So this is how we can create a calculator program using a switch case in Swift programming language. It is the most commonly used program by students to understand the working of the original calculator device or to understand the basic arithmetic operations, as well as to create their own calculator. Both methods serve their purpose very well. In these methods, you can add more operations like square root, power, etc.

Updated on: 08-Sep-2023

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements