Write JavaScript code to solve the following problems (you may recognise these …). Where a code asks for numerical input from a user you can just ‘hard-code’ this input into your answer:
-
Write some code to print out all the numbers from 1 to 10
-
Write some code that prints out only the even numbers between 1 and 10
-
Write some code that prints out only the even numbers between 1 and 1000
-
The opposite of a number is the number itself with its sign reversed. For example, the opposite of 1 is -1. The opposite of -6 is 6. Write some code that takes a numerical value and prints out the opposite of that number.
-
Write some code that prints out the numbers between 1 and 1000, but if the number is divisible by 3 it prints ‘fizz’, if the number is divisible by 5 it prints ‘buzz’ and if the number is divisible by 3 and 5 it prints ‘fizzbuzz’
-
A square number is the product of a number multiplied by itself. Write some code that takes a numerical value and prints out all the square numbers below that value.
-
The Fibonacci sequence starts with the values 1, 2. The next number in the sequence is generated by summing the previous 2 values, so the first 5 numbers in the sequence are:
1, 2, 3, 5, 8, …
a. Write some code to generate the first 100 values in the Fibonacci sequence
b. Write some code to add up only the even values in the first 1000 values of the Fibonacci sequence -
The sum of digits of a number is found by adding all the digits of a number together. For example, the sum of digits of 234 is 2 + 3 + 4 = 9. Write some code to take a numerical value and print out the sum of digits of that number.
Next: Exercise 1B: JavaScript Problem Solving
Previous: Using functions