Loops

We use loops when we want to repeat some code or activity for some certain amount of times, or under some certain condition.

Use while loops when checking for a state, and use for loops when you know how many times you want to run a loop.

While Loops

Runs while a condition is true, and stops when the condition is false.

Issues: If you forget to increment the condition, then the code continues to run, creating an infinite loop

while(condition){
some code;
incrementcondition;
}

Loop Controls

Beer Bottle Lyrics

The lyrics to 99 Bottles of beer can be used to create a function that counts down from some given number.

Note! In this case, if I were publishing these lyrics to a text file, I would use a \n newline character, but have opted to use < br> instead as to separate the lines when displayed in html.

check output in console, or right here.

For Loops

Creates a loop that starts, ends, and has some change. Used for when we want to do something for some number of times that we know.

for(start; end; increment){somecode;}

The increment increases at the end of the current iteration of the loop.

It is possible to count in either direction, and use different increments as well.

Note! If you start counting from 0, your stop condition will be x < stop. If you start counting from 1, your stop condition will be x <= stop.

Fibo Code Challenge

Take two numbers, and every number after that adds the previous two numbers in the sequence. First two numbers are [0, 1]

Bonus reading on finding the last elements of an array -> read about it here.

Results for fibbo here