A factorial program that I wrote using JavaScript as my programming language what does the program will do is to ask the user to enter a number and then our program will compute the factorial value in a given number by the user.
If you have some questions please send me an email at jake.r.pomperada@gmail.com and jakerpomperada@yahoo.com. My mobile number here in the Philippines is 09173084360.
Sample Program Output
Program Listing
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial Solver in Javascript</title>
</head>
<style>
body,label {
background-color:lightgreen;
font-family:arial;
color:blue;
font-size:18px;
font-weight:bold;
}
label{
display: table-cell;
text-align: right;
}
input {
display: table-cell;
}
div.row{
display:table-row;
}
button {
font-family: 'arial';
font-size:18px;
color:red;
}
input[type="number"] {
font-family: 'arial';
font-size:18px;
color:red;
height: 25px;
width: 38px;
}
</style>
<body>
<h2> Factorial Solver in Javascript </h2>
<div class="row"><label>Enter a Number</label>
<input type="number" size="2" id="values" maxlength="2" onkeypress="return isNumber(event)"
required autofocus><br></div>
<br>
<button title="Click here to find the factorial value.">Solve Factorial</button>
<button title="Click here to clear the text box.">Clear</button><br>
<br><br>
<div id="result"></div>
<script>
var button = document.getElementsByTagName('button');
button[0].onclick = display_result;
button[1].onclick = clear_text;
document.onload = function() {
document.getElementById('values').focus();
};
// function to compute the factorial value of a given number.
function find_factorial_value(number_value)
{
if (number_value < 0) {
return -1;
}
else if (number_value == 0) {
return 1;
}
else {
return (number_value * find_factorial_value(number_value - 1));
}
}
// This function will display the computed factorial results.
function display_result() {
var numbers = document.getElementById("values").value;
var result = find_factorial_value(numbers);
if (document.getElementById("values").value == '') {
alert("Cannot be empty. Please put a numerical value.");
document.getElementById('values').focus();
}
else {
document.getElementById('result').innerHTML = "The factorial value of "
+ numbers + " is " + result + ".";
}
}
// This function will clear the text box.
function clear_text() {
document.getElementById("values").value="";
document.getElementById("result").innerHTML="";
document.getElementById("values").focus();
}
// This function will only allow numerical value in the text box.
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
</body>
</html>
No comments:
Post a Comment