IT Beginner Series: JavaScript FOR Loop Exercises (3)
More in the IT Beginner Series
Introduction
For loops are used to execute a piece of code a desired numbers of times. They are generally used to iterate over lists/collections of items. Think about iterating over a list of students and executing a piece of code that calculates the average grade for each student.
Loops and arrays are a great way to make you code adapt to change. Written correctly, a for loop will execute code no matter if you have one or 1 million students or if the number of students fluctuates over time(which will surely happen as they are students, right?:))
Syntax
//A for loop that counts from 0 to 100 looks like thisfor(var i = 0; i <= 100; i++){
//your code that will be executed 100 times here
}
A for loop has 3 parts:
- a starting point: var i = 0
- a stop/end point i ≤ 100
- a “step” i++ (a short version of i = i+1)
Starting from 0(var i=0), the for loop will increase the value of i with the specified “step” after each execution(i++). It will continue to do so until the expression i<= 100 is false, thus finishing it’s execution.
Exercises with solution
#1 — Print the numbers from 0 to 15
Solution
for (var i = 0; i <= 15; i++) {
console.log("Value of i is: " + i);
}
#2 — Print the numbers from 12 to 24
Solution
for (var i = 12; i <= 24; i++) {
console.log("Value of i is: " + i);
}
#3 — Print the ODD numbers from 7 to 31
Solution
for (var i = 7; i <= 31; i++) {
if (i % 2 != 0) {
console.log(i);
}
}
#4 — Print the EVEN numbers from 10 to -20
Solution
for (var i = 10; i >= -20; i--) {
if (i % 2 == 0) {
console.log(i);
}
}
#5 — Iterate through all numbers from 1 to 45. Print the following:
- For multiples of 3 print “Fizz”
- For multiples of 5 print “Buzz”
- For multiples of 3 and 5 print “FizzBuzz”
Solution
for (var i = 1; i <= 45; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log("FizzBuzz");
} else if (i % 3 == 0) {
console.log("Fizz");
} else if (i % 5 == 0) {
console.log("Buzz");
}
}
#6 — Print all the elements of the following array
var thisIsAnArray = ["element1", "element2", "element3", "element4"];
Solution
var thisIsAnArray = ["element1", "element2", "element3", "element4"];for (var i = 0; i < thisIsAnArray.length; i++) {
console.log(thisIsAnArray[i]);
}
#7 — Calculate the sum of all the numbers in the following array
var numbersArray = [1,13,22,123,49]
Solution
var numbersArray = [1, 13, 22, 123, 49];var sum = 0;for (var i = 0; i < numbersArray.length; i++) { sum = sum + numbersArray[i];}console.log("The sum is: " + sum);