
Simple Calculator in HTML using for loops
Sure! Here’s an example of a simple calculator in HTML using for loops:
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<style>
.container {
width: 200px;
margin: 0 auto;
}
.btn {
width: 50px;
height: 50px;
margin: 5px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="result" readonly>
<br>
<button class="btn" onclick="calculate('+')">+</button>
<button class="btn" onclick="calculate('-')">-</button>
<button class="btn" onclick="calculate('*')">*</button>
<button class="btn" onclick="calculate('/')">/</button>
<br>
<button class="btn" onclick="clearResult()">Clear</button>
</div>
<script>
function calculate(operator) {
var numbers = document.querySelectorAll('input[type="number"]');
var result = document.getElementById('result');
var total = parseFloat(numbers[0].value);
for (var i = 1; i < numbers.length; i++) {
var number = parseFloat(numbers[i].value);
switch (operator) {
case '+':
total += number;
break;
case '-':
total -= number;
break;
case '*':
total *= number;
break;
case '/':
total /= number;
break;
}
}
result.value = total;
}
function clearResult() {
var result = document.getElementById('result');
result.value = '';
}
</script>
</body>
</html>
In this example, we have a simple calculator with four arithmetic operations: addition, subtraction, multiplication, and division. The numbers to be calculated are entered in input fields, and the result is displayed in a readonly text field.
The calculate()
function is called when one of the operation buttons is clicked. It retrieves the input values, performs the calculation using a for loop and a switch statement based on the selected operator, and updates the result field.
The clearResult()
function clears the result field when the “Clear” button is clicked.
Note: This is a basic example for demonstration purposes. In a real-world scenario, you may need to add error handling, validation, and additional features to make the calculator more robust and user-friendly.