In: Computer Science
You should use Visual Studio to write and test the program from this problem.
Write a complete program with a for loop that
Following is the code and output screenshot along with comments
in the code.
<!-- HTML5 Structure is as follows -->
<!DOCTYPE html>
<!-- It is your choice to set langugae as english or any other language that you would like. -->
<html lang="en">
<!-- Here is the head part, where we give title to the project of file and add all the links/ scripts that we need to use in our project. -->
<head>
<!-- meta tags are just used to tell the search engines what kind of content we are offering in our project and charset defines the documents character set. -->
<meta charset="UTF-8">
<!-- Here you can give a title to your project. -->
<title>Web App</title>
</head>
<body onload="getData()">
<!-- We will be displaying result here. -->
<div id="result"></div>
<!-- Adding a script tag here for javascript function that we are going to run on page load. -->
<script>
//Creating a function here to display the result on screen based on for loop on page load.
function getData() {
let numArr = [1, 2.1, 1.2, 3, 4, 5, 7, 6]; //Creating array of real numbers(8 items) to sum up using a for loop.
let sum = 0;//Initialise the sum to 0.
let count = 0; //Initialising the count to 0.
// Applying a for loop on the numArr till count is 8 and printing the result on the screen.
for (count; count <= 8; count++) {
sum = sum + numArr[count]; //Adding the array items till count is 8
// Checking if count is till index 7 which counts till 8 and displaying the data on screen upto two decimal points.
if (count == 7) {
sum = sum / numArr.length; //Getting the average of the sum by dividing the sum with the count.
document.getElementById("result").innerHTML = sum.toFixed(2); //Displaying the result on screen using document upto 2 decimals.
}
}
}
</script>
</body>
</html>
Here is the Output.
I hope you find the answer helpful. I have added comments along
with code. In case you have any doubt, please let me know in the
comment section below. Also, please give it a thumbs up. Thank
you.