In: Computer Science
For both JavaScript and HTML:
----------------------------------------------------
Write and test JavaScript scripts for the two exercises that follow, debug (if necessary). When required to write a function, you must include a script to test the function with at least two different data sets. In all cases, for testing, you must write an HTML file that references the JavaScript file.
// Code for question1
<!DOCTYPE html>
<html>
<body>
<!-- creating table with solid border -->
<table style="border: solid;">
<!-- creating row with three
headers -->
<tr>
<th>Number</th>
<th>Square</th>
<th>Cube</th>
</tr>
<!-- creating rows with their three datas: number, square and cubes -->
<tr>
<td>2</td>
<td>4</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>9</td>
<td>27</td>
</tr>
<tr>
<td>4</td>
<td>16</td>
<td>64</td>
</tr>
<tr>
<td>5</td>
<td>25</td>
<td>125</td>
</tr>
<tr>
<td>6</td>
<td>36</td>
<td>216</td>
</tr>
<tr>
<td>7</td>
<td>49</td>
<td>343</td>
</tr>
<tr>
<td>8</td>
<td>64</td>
<td>512</td>
</tr>
</table>
</body>
</html>
// Screenshot for question1
// output for question1:
// QUESTION2 SOLUTION:
// counter.js file for question2 which has the implementation of counter function
// Creating a function counter which takes an array arr of number as a parameter
function counter(arr){
// intializing counter variable of negative number,
positive number and zero to 0
var negativeCount = 0;
var positiveCount = 0;
var zeroCount = 0;
var i;
// start counting
for(i=0; i < arr.length; i++){
// if number is zero increment
zeroCount
if(arr[i] == 0)
zeroCount++;
// if number is negative
increment negative count
else if(arr[i] < 0)
negativeCount++;
// else increment positive
count
else
positiveCount++;
}
// now create an array having all three count as
elements
//var tempArr = new Array(positiveCount, zeroCount,
negativeCount);
var tempArr = [];
tempArr[0] = negativeCount;
tempArr[1] = zeroCount;
tempArr[2] = positiveCount;
// now return the tempArr
return tempArr;
}
// Screenshot for counter.js file
// Html code to test the counter function
<!DOCTYPE html>
<html>
<head>
<!-- Import the counter.js file -->
<script src="counter.js"></script>
</head>
<body>
<h1>Test1 output: </h1>
<p id="test1"></p>
<h1>Test2 output: </h1>
<p id="test2"></p>
<!-- Writing script to check the counter
function of couter.js file -->
<script >
// test 1
var tempArr = counter([1, 2, 0, 0,
5, -1, -3, -4, 0, 4, 0, 0]);
document.getElementById("test1").innerHTML = "Negative count is: " + tempArr[0] + "<br>" + "Zero count is: " + tempArr[1] + "<br>" + "Positive count is: " + tempArr[2];
// test 2
var tempArr = counter([13, 23, 9,
0, 5, -1, -3, -4, 0, 4, 0, 0, -99, 0, 76]);
document.getElementById("test2").innerHTML = "Negative count is: " + tempArr[0] + "<br>" + "Zero count is: " + tempArr[1] + "<br>" + "Positive count is: " + tempArr[2];
</script>
</body>
</html>
// screenshot for HTML test file of counter function
// OUTPUT for question2 after running html test file