Member-only story
The "While" Loop
A "While" Loop is used to repeat a specific block of code an unknown number of times until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10." If we (or the computer) know exactly how many times to execute a section of code (such as shuffling a deck of cards), we use a for loop.
The While Loop
The while loop is used to repeat a section of code an unknown number of times until a specific condition is met. For example, say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. If we know a specific number, such as 32, we can say 5 times, but for a given symbolic variable "NUMBER," which represents any number in the world, how many times is not known a priori (beforehand). In this case, we could use a while loop to determine that answer:
The "pseudocode" for such an algorithm is: while the number is bigger than one, keep dividing it by two. Additionally, keep a count of how many times we do the division.
numberr set our initial count to 0 while our number is greater than 1 divide the number by 2 increase our count by 1end end