Parts of a While Loop
There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times.
Three main pieces of information that any loop should have are:
- When to start: The code that sets up the loop — defining the starting value of a variable for instance.
- When to stop: The logical condition to test whether the loop should continue.
- How to get to the next item:
The incrementing or decrementing step — for example,
x = x * 3
orx = x - 1
Here's a basic while loop example that includes all three parts.
var start = 0; // when to start
while (start < 10) { // when to stop
console.log(start);
start = start + 2; // how to get to the next item
}
Prints:
0
2
4
6
8
If a loop is missing any of these three things, then you might find yourself in trouble. For instance, a missing stop condition can result in a loop that never ends!
Directions:
Write awhile
loop that:
- Loop through the numbers 1 to 20
- If the number is divisible by 3, print
"Julia"
- If the number is divisible by 5, print
"James"
- If the number is divisible by 3 and 5, print
"JuliaJames"
- If the number is not divisible by 3 or 5, print the number
/*
* Programming Quiz: JuliaJames (4-1)
*/
var num = 1;
while (num <= 20) {
if ( num % 3 === 0 && num % 5 === 0 ) {
console.log("JuliaJames");
} else if ( num % 3 === 0 ) {
console.log("Julia");
} else if ( num % 5 === 0 ) {
console.log("James");
} else {
console.log( num );
}
num = num + 1;
}