Exercise 16: Simple Calculator with if/else
Build a basic calculator using if/else conditional structures. Ideal for practicing operations and programming logic.
The primary objective is to practice using if/else statements.if/elseto perform basic mathematical operations according to the user's choice.
Activity
-
Ask the user to enter two numbers and an operation (
+,-,*,/). -
Use
if/elseTo perform the correct operation:
Add if you choose+Subtract if you choose-Multiplication if you choose*Division if you choose/
- Display the result in the console.
Solution
Step 1: Create the index.html file
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calculadora Sencilla con if/else</title>
</head>
<body>
<h1>Ejercicio 16: Calculadora Sencilla con if/else</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
JavaScript
let numero1 = parseFloat(prompt("Ingresa el primer número:"));
let numero2 = parseFloat(prompt("Ingresa el segundo número:"));
let operacion = prompt("Ingresa la operación (+, -, *, /):");
if (operacion === "+") {
console.log("Resultado:", numero1 + numero2);
} else if (operacion === "-") {
console.log("Resultado:", numero1 - numero2);
} else if (operacion === "*") {
console.log("Resultado:", numero1 * numero2);
} else if (operacion === "/") {
console.log("Resultado:", numero1 / numero2);
} else {
console.log("Operación no válida.");
}
info
🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.