In: Computer Science
Activity 11: JS-Loops and Functions
Task 1:
Use JavaScript for loop to print the first 5 non-zero integers on
each line.
Task 2:
Use JavaScript while loop to print the first 5 non-zero integers on
each line.
Task 3:
Use JavaScript for loop to print the first 5 even integers on each
line.
Task 4:
Write a JavaScript function to multiple two numbers and return the
result.
Task 5:
Write a JavaScript factorial that asks users to enter a positive
and return the result.
i) Without using recursion ii) Using recursion Task 6:
Use a nested for or while loop to produce a table below.
1,1 1,2 1,3 1,4 1,5
2,1 2,2 2,3 2,4 2,5
3,1 3,2 3,3 3,4 3,5
4,1 4,2 4,3 4,4 4,5
5,1 5,2 5,3 5,4 5,5
1) var i;
for (i = 0; i <= 5; i++) {
console.log(i + 1);
}
2)
var i = 0;
while (i <= 5) {
console.log(i + 1);
i++;
}
3)
for (i = 1; i <= 10; i++) {
if(i % 2 == 0)
{
console.log(i);
}
}
4)
function prod(p1, p2) {
return p1 * p2; // The function
returns the product of p1 and p2
}
5)
//Using recursion
function factorial(n) {
if(n == 0)
{
return 1;
}
return n * factorial(n - 1);
}
//Without recursion
function factorial(n) {
var prod = 1;
for(i = 1;i <= n;++i)
{
prod *= i;
}
return prod;
}
6)
var i = 1;
var j = 1;
var text = "";
for(i = 1;i <= 5;i++)
{
text = "";
for(j = 1;j <= 5;j++)
{
text += " " + i + "," + j + " ";
}
console.log(text);
}
OUTPUT: