Prepin
Log in

Create a Calculator

Approach / Explanation

This question requires you to create an algorithm for a calculator. The calculator must be capable of performing basic mathematical operations such as addition, subtraction, multiplication, and division. It can include functions like add(), subtract(), multiply(), and divide(), which will accept two numbers as arguments and return the computed result. Here are some guidelines for addressing this question: Define each function to accept two parameters. Each function should execute the corresponding mathematical operation and return the outcome. You may adopt an object-oriented approach by organizing all these functions within a class named Calculator. Be sure to account for division by zero scenarios.

Suggested Answer

Below is a straightforward implementation of a Calculator in Python: class Calculator : def add ( self , a , b ) : return a + b def subtract ( self , a , b ) : return a - b def multiply ( self , a , b ) : return a * b def divide ( self , a , b ) : if b == 0 : return "Error: division by zero" else : return a / b This example demonstrates four fundamental operations as individual methods within a Calculator class. Each method accepts two numbers as arguments and returns the outcome of the respective operation. The divide method includes a check for division by zero and addresses it appropriately.

Alternative Answer

Here is an alternative method for creating a Calculator with JavaScript: class Calculator{ add(a, b){ return a + b; } subtract(a, b){ return a - b; } multiply(a, b){ return a * b; } divide(a, b){ if(b == 0){ return "Error: division by zero"; } else { return a / b; } } } This JavaScript example demonstrates the calculator's functionality using a class-based approach, akin to the Python version. Furthermore, the divide() method includes a check to avoid division by zero, providing an error message if that scenario arises.

Question Details

Difficulty & Category

Medium
algorithms

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.