Ajp Practical 4
Ajp Practical 4
Defining a Function
3. True or False.
A function can be called by HTML code in a web page.
a. True b. False
192020058
Exercise:
Calculate the factorial of a number by
1) calling function without argument
Code
<html>
<head>
<title>
factorial of a given number
</title>
</head>
<body>
<center>
<h2>Javascript Factorial</h2>
<button onclick="myFunction()">Promt Button</button>
<script>
function myFunction() {
var i;
var fact = 1;
var number = prompt("Please enter a number")
for(i = 1;i <= number;i++) {
fact = fact * i;
}
document.write("Factorial of "+number+" is "+fact);
}
</script>
</body>
</html>
Output
192020058
2) calling function with argument.
code
<html>
<head>
</head>
<body>
Enter a number: <input id="number">
<br><br>
<button onclick="fact1()"> Factorial </button>
<p id="res"></p>
<script>
function fact(num) {
if (num == 0) {
return 1;
}
else {
return num * fact(num - 1);
}
}
function fact1() {
var num = document.getElementById("number").value;
var f = fact(num);
document.getElementById("res").innerHTML = "The factorial of the number
" + num + " is: " + f;
}
</script>
</body>
</html>
Output: -
192020058
Conclusion:
We have learnt about how to print message and how to perform Factorial
operation using alert and prompt.
192020058