🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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 + 3Output:
8Input:
10 / 2Output:
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
num1andnum2and an operator (e.g.,+,-,*,/) from the user.
Step 2: Perform the Arithmetic Operation
- The
switchstatement 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment