Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Practice Programs
  5. Basic Calculator operations using switch..case

Basic Calculator operations using switch..case

Example: 2B

Write a JavaScript for performing calculator operations (+, -, *, /) using switch..case

Script

const prompt = require("prompt-sync")();

let operator = prompt("Enter the operator (+, -, *, /) :");
let n1 = prompt("Enter the number : ");
n1 = parseInt(n1);
let n2 = prompt("Enter the number : ");
n2 = parseInt(n2);
let res;

switch (operator) {
  case "+":
    res = n1 + n2;
    console.log(`${n1} ${operator} ${n2} = ${res}`);
    break;
  case "-":
    res = n1 - n2;
    console.log(`${n1} ${operator} ${n2} = ${res}`);
    break;
  case "*":
    res = n1 * n2;
    console.log(`${n1} ${operator} ${n2} = ${res}`);
    break;
  case "/":
    res = n1 / n2;
    console.log(`${n1} ${operator} ${n2} = ${res}`);
    break;
  default:
    console.log("Operator is not specified");
    break;
}

Output

Loading

Views: 8

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments