Introduction
A basic calculator allows the user to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. In JavaScript, you can easily create a calculator that accepts two numbers and performs the desired operation based on user input. This guide will walk you through writing a JavaScript program to implement a basic calculator.
Problem Statement
Create a JavaScript program that:
- Accepts two numbers and an operator from the user.
- Performs the arithmetic operation (addition, subtraction, multiplication, division) based on the operator.
- Displays the result of the operation.
Example:
Input:
5 + 3
Output:
8
Input:
10 / 2
Output:
5
Solution Steps
- Initialize the Numbers and Operator: Accept two numbers and an operator (+, -, *, /) from the user.
- Perform the Operation:
- Based on the operator, perform the arithmetic operation (addition, subtraction, multiplication, division).
- Display the Result: Output the result of the operation.
JavaScript Program
// JavaScript Program to Implement a Basic Calculator
// Author: https://www.rameshfadatare.com/
function calculator(num1, num2, operator) {
let result;
// Step 2: Perform the arithmetic operation based on the operator
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 === 0) {
console.log("Error: Division by zero is not allowed.");
return;
}
result = num1 / num2;
break;
default:
console.log("Error: Invalid operator");
return;
}
// Step 3: Display the result
console.log(`Result: ${num1} ${operator} ${num2} = ${result}`);
}
// Example usage
const num1 = 10;
const num2 = 5;
const operator = '*';
calculator(num1, num2, operator);
Explanation
Step 1: Accept the Numbers and Operator
- The program accepts two numbers
num1
andnum2
and an operator (e.g.,+
,-
,*
,/
) from the user.
Step 2: Perform the Arithmetic Operation
- The
switch
statement is used to check the operator and perform the appropriate arithmetic operation. The four operations handled are:+
for addition-
for subtraction*
for multiplication/
for division (with a check to avoid division by zero)
Step 3: Display the Result
- The result of the operation is displayed using
console.log()
.
Output Example
Result: 10 * 5 = 50
Example with Different Input
const num1 = 20;
const num2 = 4;
const operator = '/';
calculator(num1, num2, operator);
Output:
Result: 20 / 4 = 5
Handling Division by Zero
In case of division by zero, the program will display an error message:
Error: Division by zero is not allowed.
Basic Calculator with User Input in HTML
You can also create a simple calculator that accepts input from the user via an HTML form.
HTML and JavaScript Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Calculator</title>
</head>
<body>
<h1>Basic Calculator</h1>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
<script>
function calculate() {
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);
const operator = document.getElementById("operator").value;
let result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 === 0) {
document.getElementById("result").textContent = "Error: Division by zero";
return;
}
result = num1 / num2;
break;
default:
document.getElementById("result").textContent = "Invalid operator";
return;
}
document.getElementById("result").textContent = `Result: ${num1} ${operator} ${num2} = ${result}`;
}
</script>
</body>
</html>
Explanation of HTML Example
- The user can input two numbers and select an operator using a dropdown menu.
- When the "Calculate" button is clicked, the
calculate()
function is called, which performs the arithmetic operation and displays the result on the webpage.
Output in Browser
The result will be displayed in the <p>
element when the user clicks the "Calculate" button.
Conclusion
This JavaScript program implements a basic calculator that performs addition, subtraction, multiplication, and division operations. The example can be further enhanced by adding more features like handling edge cases or creating a graphical user interface using HTML and JavaScript for user interaction.
Comments
Post a Comment
Leave Comment