JavaScript Loops
Write a JavaScript program to print the multiplication table of a number
Description: Print the multiplication table of 7, from 1 to 10.
Hint:
- Use a
forloop from 1 to 10.
JavaScript multiplication table program
const num = 7;
for (let i = 1; i <= 10; i++) {
console.log(`${num} x ${i} = ${num * i}`);
}
Output:
Tutorials Class - Output Window
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
How it works
- The loop runs with
ifrom 1 to 10. - The template literal prints the line with the numbers.
Read JavaScript Loops.
Write a JavaScript program to find the factorial of a number
Description: Find the factorial of 5 in two ways: with a loop and with a recursive function.
Hint:
- Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
- A recursive function needs a base case.
JavaScript factorial program
// loop
let fact = 1;
for (let i = 1; i <= 5; i++) {
fact *= i;
}
console.log(fact);
// recursion
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
console.log(factorial(5));
Output:
Tutorials Class - Output Window
120
120
How it works
- The loop multiplies
factwith 1, 2, 3, 4 and 5. - The recursive function calls itself with a smaller number until it reaches the base case.
Read JavaScript Functions.
Write a JavaScript program to print the Fibonacci series
Description: Print the first 10 numbers of the Fibonacci series.
Hint:
- Each number is the sum of the two before it.
- Start with 0 and 1.
JavaScript Fibonacci program
let a = 0, b = 1;
const series = [];
for (let i = 0; i < 10; i++) {
series.push(a);
[a, b] = [b, a + b];
}
console.log(series.join(", "));
Output:
Tutorials Class - Output Window
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
How it works
[a, b] = [b, a + b]moves to the next pair.join(", ")makes one text from the array.
Write a JavaScript program to check prime number
Description: Check whether the numbers 2, 15, 17 and 1 are prime.
Hint:
- A prime number is greater than 1 and has no divisor other than 1 and itself.
- Test divisors up to the square root.
JavaScript prime number program
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
for (const n of [2, 15, 17, 1]) {
console.log(n + (isPrime(n) ? " is prime" : " is not prime"));
}
Output:
Tutorials Class - Output Window
2 is prime
15 is not prime
17 is prime
1 is not prime
How it works
- Numbers below 2 are not prime.
- For 15 the loop finds that
15 % 3 === 0and returnsfalse. - As soon as one divisor is found, the function returns.