Whenever I think of using the while loop, I don’t see why I can’t just use an if statement instead. I know that a while loop runs ‘while’ a given statement is true, but if the condition is terminated inside the block instantaneously, then I cannot visualize anything happening ‘while’ something is true. If anyone can give me examples of how/why I should use a while loop. It would be very appreciated.
Whenever I think of using the while loop , I don’t see why I
Share
I’m going to try to give you a very high-level answer because I think it will be easier to grasp intuitively.
Think of all algorithms as recipes. A typical recipe might have parts that look like the following:
These types of directions have you do tasks in different ways.
The first one is really an “if” statement. You do something if a condition (peanut has a shell) is true. You literally do:
The second one is a while loop. You beat the egg while it is not whipped and bubbly. You do the same thing over and over (whipping) continuously, and you look at it (over and over) when doing this to check and see if it has turned very bubbly. Once it gets bubbly and whipped enough, you stop. When you stop it is because you have passed your “While” condition. An important thing to note is that before you start, you don’t necessarily know just how many “beats” of an egg it takes to get it whipped. You just have to do it many times and check (with your eyes) many times. You literally do:
Just like in recipes, you don’t want someone doing a certain action until the end of time, so you must always make sure your while loops have sensible stopping conditions. Most while loops depend on something changing inside of the loop and will stop when that thing has changed enough.
The third recipe example is a for loop. For each onion you have (5) you do something once to that one onion. You literally do: