6.11 Iterate with a while loop - Video Tutorials & Practice Problems
Video duration:
1m
Play a video:
Video transcript
<v Voiceover>Sometimes</v> when building a loop, you don't know how many iterations you're going to need. You want it to keep running while some statement is true. That's where the while loop comes in. It's fairly simple to write. Every time it iterates, it checks some value and if it's true, it continues. So let's establish some starting value x gets one and now let's build a while loop. While x is less than or equal to five, print out x and as you print it, do x plus one, this way x keeps growing. So what we expect to happen is this will print out the first five numbers and then stop because x became six. Let's see if that happens and there you have it. It printed out one, two, three, four, five. This check right here can be any type of check. It could be a compound statement, it could be something complex, something simple, and the while loop can perform any iterations. It is important to remember that if you don't have a good checking statement, you could get into an infinite loop and just crash the program. So make sure you're checking for something that is appropriate. So that's a quick look at while loops. They're probably one of the least used features, at least for me, but they do come in handy every now and then. So support as you remember, all you're doing is checking a statement, performing an operation, and continuing, as long as that statement is true.