The while loop works on a condition (or multiple conditions)
while ((x <= 5) && (paused == false)) {
// do something
}
A lot of the time, it involves a counting variable - doing the loop a certain number of times
while (count < 100) {
// do something
}
But many programmers forget to modify the counting variable, causing an infinite loop!
Enter: The For Loop
If you know you'll be counting - maybe going through a string or list - you could use the for loop.
for (part1; part2; part3) {
// Your code
}
part1
is the declaration of any indexer or counting variable. Example:let i = 0;
part2
is exactly like thewhile
condition. Example:i < 10;
(which means whilei
is less than 10)part3
is what will happen to the indexer on each loop iteration. Example:i++
(increasei
by 1) or maybei += 3
(add 3 toi
) on each iteration
for (let i = 100; i > 0; i--) {
// Count down from 100 to 1
}
for (let j = 10; j <= 30; j += 2) {
// Count up by 2's from 10 to 30
}
for (let x = 93; x > 51; x -= 5) {
// Count down by 5's from 93 to 51
}
Print from 0% to 100% going up by 2.5%
for (let p = 0; p <= 100; p += 2.5) {
console.log(p + "%");
}
// Output:
0%
2.5%
5%
...
97.5%
100%
Print the alphabet on one line using the character codes:
let alpha = "";
for (let letter = 65; letter < 91; letter++) {
alpha += String.fromCharCode(letter);
}
console.log(alpha);
// Prints ABCDEFGHIJKLMNOPQRSTUVWXYZ
Make a new coding file called 3.3 - For Loops.js
. Complete the following in that file. Assume the function parameters are proper numbers (no need for error-checking).
- Write the function
countUp(start, stop)
that prints fromstart
tostop
(inclusive) on the console. Example:
> countUp(5, 8)
5
6
7
8
- Write the function
countDown(start, stop)
that prints down fromstart
tostop
on the console. Example:
> countDown(10, 6)
10
9
7
6
-
Write the function
sum(n)
which returns the sum (addition) from 1 ton
. Use a for-loop to complete it.
For Example:sum(7)
returns 28 (because 1+2+3+4+5+6+7 = 28) -
Write the function
count4(begin, end)
that returns how many numbers are divisible by 4 frombegin
toend
(inclusive). Use a for-loop to complete it.
For Example:count4(5, 43)
returns 9 (because 8, 12, 16, 20, 24, 28, 32, 36, 40) -
Write the function
sum_divisible(n, x)
which returns the sum (addition) of the values from 0 ton
that are divisible byx
.
For Example:sum_divisible(32, 6)
returns 90 (because 6+12+18+24+30 = 90)