Loops: While and Do-While

While loops are useful when the number of times the loop should repeat is not known. It will execute as long as a certain example is true, and checks the loop condition before each iteration of the code inside. For example, in the following code, the loop will continue to run until the number of consecutive heads is less than 3.



Do-While loops are different from While loops in that they always run the code inside the loop at least once, checking the condition after the initial loop to see if it should continue to keep looping. For example, in the following code, the loop condition is false - but because the loop does not check the condition until after it has run, it executes once anyway. It will print "The loop ran even though the loop condition is false." and then "Now the loop is done running.", signifying it has exited the loop.