Lesson 22: While Loops

In the last lesson, we learned about increment and decrement operators and how we can use them to add or take away values.  In this lesson, we are going to further explore the usage of the increment operator and learn about while loops.

A While loop is a loop that will continue to run until the condition is false.  Look at the code below to see an empty while loop.

The reserved word while, precedes a set of parenthesis, which is followed by a set of brackets.  Similarly to the if statement, the condition is put into the parenthesis, and the brackets contains the code we want executed if the condition is true.

Now that we know what the setup looks like, let’s go over an example.

As we can see in the code above, we have the while loop run until the numOfChairs is equal to the numOfGuests.  Then, once the numOfChairs is equal to the numOfGuests, the if statement below prints out how many chairs are present.  Look at the output below.

As we can see, the while loop continues to loop until the conditional statement no longer evaluates to true.  In this case, it is when the numOfChairs is no longer less than the numOfGuests.

When using while loops, it is important to have an obtainable end-state, otherwise the program will never end.  For example, if we were to change numOfChairs++ to numOfChairs-- , it would loop forever because the condition would always be true.

One last note, is that if the condition of the while statement does not evaluate to true, then the code inside it will not execute at all.  See you next lesson!

GitHub link.

Leave a Reply

%d bloggers like this: