Write a Javascript Program (1 HTML File) that will input an integer value n and display (upon a button click) the following:
1. The nth factorial (Using a While Loop)
2. The sum of the first n numbers (Using a Do While Loop)
3. The Average of the first n numbers (Using a For Loop)
<html>
<head>
<title>Average</title>
<script language="javascript" type="text/javascript">
window.onload = function () {
btnCalculate.addEventListener("click", displayResult);
function displayResult() {
if (txtN.value == "") {
alert("Enter N!!!")
return;
}
let N=parseInt(txtN.value);
let factorial=1;
let i = 1;
while(i <= N) {
factorial = factorial * i;
i++;
}
let sum=0;
i=0;
do{
sum+=i;
i++;
}while(i<=N);
sum=0;
for(i=0;i<=N;i++){
sum+=i;
}
let average=sum/N;
txtFactorial.value=factorial;
txtSum.value=sum;
txtAverage.value=average.toFixed(2);
};
}
</script>
</head>
<body>
<form>
<table>
<tr>
<tr>
<td>Enter N</td>
<td> <input id="txtN" type="text" value=""></td>
</tr>
<tr>
<td>The nth factorial:</td>
<td> <input id="txtFactorial" type="text" value="" readonly></td>
</tr>
<tr>
<td>The sum of the first n numbers:</td>
<td> <input id="txtSum" type="text" value="" readonly></td>
</tr>
<tr>
<td>The Average of the first n numbers:</td>
<td> <input id="txtAverage" type="text" value="" readonly></td>
</tr>
<tr>
<td></td>
<td> </td>
</tr>
<tr>
<td></td>
<td><input id="btnCalculate" type="button" value="Calculate"></td>
</tr>
</table>
</form>
</html>
Comments
Leave a comment