FOR FREE CONTENT

Basic Calculator

Back to Programming

Description

In this program, a basic calculator is designed to perform the four basic mathematical operations i.e. addition, subtraction, multiplication and division according to the user’s choice. Two numbers are taken as inputs and the operations are performed according to the choice and the output is displayed. Before division, the value of the divisor is checked. If the value of the divisor is 0 then the division is not possible. 

 

Let the two given numbers are 3 and 5.

# If the choice is 1, then the two numbers will be added, the output will be: 3 + 5 = 8.

 

# If the choice is 2, then the two numbers will be subtracted, the output will be: 3 – 5 = -2

 

# If the choice is 3, then the two numbers will be multiplied, the output will be: 3 × 5 = 15

 

# If the choice is 4, then the two numbers will be divided, the output will be: 3 / 5 = 0

Algorithm

INPUT: Two Numbers and the choice

OUTPUT: The result after performing addition/ subtraction/ multiplication/ division.

PROCESS:

Step 1: [Taking the inputs]

               Print “1. Add

          2. Subtract

          3. Multiplication

          4. Division

          Enter your choice: “

Read ch [the choice]

Read a, b [the two numbers]

Step 2: [Performing the operations]

               If ch=1 then

                              Print “the sum is: a+b”

               Else if ch=2 then

                              Print “the difference is: a-b”

               Else if ch=3 then

                              Print “the product is: a×b”

               Else if ch=4 then

                              If b≠0 then

                                             Print “The result after division: a/b”

                              Else

                                             Print “The division is not possible”

                              [End of ‘if’]

               Else

                              Print “Wrong Choice”

               [End of ‘if’]

Step 3: Stop.

Code

TIME COMPLEXITY:

if ch==1: --------------------------------------- O(1)

    print("\nThe sum is: ",a+b)

#subtraction

elif ch==2: ------------------------------------- O(1)

    print("\nThe difference is: ",a-b)

#multiplication

elif ch==3: -------------------------------------- O(1)

    print("\nThe product is: ",a*b)

#division

elif ch==4: -------------------------------------- O(1)

    if b!=0:

        print("\nThe quotient is: ",a/b)

    else: ------------------------------------------- O(1)

        print("\nThe division is not possible")

 

The time complexity of this program is O(1) as it requires a constant time to execute the program.

 

SPACE COMPLEXITY:

The space complexity of this program is O(1) as it requires a constant memory space to execute the program for any given input.