Exercise 1: Multiplication Table
Write a JavaScript program to print the multiplication table for a given number.
Example:
Input: 3
Output:
3 x 1 = 3
3 x 2 = 6
…
3 x 10 = 30
%%js
let number = 10;//declares number (that we later will be making a multiplication table for) as 10
let result; //makes the result variable
for (let i=1; i<=10; i++){ //repeats 10 times to make a multiplication table up to the 10s
result = number*i; //multiplies the number times i
console.log(`${number} x ${i} = ${result}`);//prints out "number x i = result" replace the variable names with the correct values
}
<IPython.core.display.Javascript object>
Exercise 2: Nested Loops
Write a JavaScript program using nested loops to generate the following pattern:
Output:
0
00
000
0000
00000
%%js
let x=5;//sets x to 5
for (let a=0; a < x; a++) { //repeats x times
let printAmount = "0";//lets the print amount equal "0"
for (let i=0; i<a; i++ ){//repeats the iteration number that the first loop is on
printAmount += "0";
}
console.log(printAmount);//prints printAmount, which is "0" the amount of times that it was repeated in the previous loop
}
<IPython.core.display.Javascript object>
Challenge Exercise: Prime Numbers
Write a JavaScript program to print all prime numbers between 1 and 50.
%%js
let x = 50; //sets x to 50, which is the amount that the program checks up to as 50
if (x <= 1){//checks if x is less than or equal to 1
console.log("No prime numbers found... :("); //prints out that there are no prime numbers because there aren't any prime numbers under 1
} else {
const primeNumbers = [];//initializes array for the list of prime numbers
for(let i = 2; i <= x; i++){//repeats from 2-50 (1 isn't prime, so we don't have to include that)
let isPrime = true;//assumes number is prime
for(let a = 2; a <= Math.sqrt(i); a++){//checks if there are factors from 2 to the square root of i, which is the number that is being checked
if (i % a === 0){//if it gives no remainder, then that number is a factor, and the number is not prime
isPrime = false;//isPrime is set to false
}
}
if (isPrime){
primeNumbers.push(i);// if the number passes all the checks, then the number is prime and is added to the array of prime numbers
}
}
console.log(primeNumbers);//prints out the array of prime numbers
}
<IPython.core.display.Javascript object>