Summations

Summations Calculator

Create a program that takes 3 inputs, a lower bound, an upper bound and the expression. Calculate the sum of that range based on the given expression and output the result.

For Example:
Input: 2 4 *2
Output: 18 (2*2 + 3*2 + 4*2)

Input: 1 5 %2
Output: 3 (1%2 + 2%2 + 3%2 + 4%2 + 5%2)

Video: https://youtu.be/WMOBJoPSxpc

summations.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Summations calculator</title>
<script src="summations.js"></script>
</head>
<body>
<p>Enter lower and upper bound</p>
<input type="text" name="lowerBound" id="lowerBound" placeholder="e.g 2">
<input type="text" name="upperBound" id="upperBound" placeholder="e.g 4">
<p>Select the expression and enter the expression value</p>
<select name="expression" id="expression">
<option value="+">+</option>
<option value="-">-</option>
<option value="/">/</option>
<option value="*">*</option>
<option value="%">%</option>
<option value="^">^ (power)</option>
</select>
<input type="text" name="exprValue" id="exprValue" placeholder="e.g 2">
<button id="btnSubmit" onclick="calculate()">Submit</button>
<p id="answer"></p>
</body>
</html>


summations.js

function calculate() {
// + is used to convert the value into int format
const lowerBound = +getElement('lowerBound').value;
const upperBound = +getElement('upperBound').value;
const exprValue = +getElement('exprValue').value;
const expression = getElement('expression').value;

let answer = 0; // this will contain the final output

// loop through the lowerBound to the upperBound for each number
for (let index = lowerBound; index <= upperBound; index++) {
// check the expression and calculate the sum accordingly
if (expression == '+') {
answer += index + exprValue;
} else if (expression == '*') {
answer += index * exprValue;
} else if (expression == '-') {
answer += index - exprValue;
} else if (expression == '/') {
answer += index / exprValue;
} else if (expression == '%') {
answer += index % exprValue;
} else if (expression == '^') {
answer += Math.pow(index, exprValue);
}
}
// this function will print the answer to the document
printAnswer(answer);
}

// this function will get element from the html document
function getElement(id) {
return document.getElementById(id);
}

function printAnswer(value) {
getElement('answer').innerHTML = value;
}


Output:





Comments

Popular Posts