While Loop

The While loop is a repetition structure where the statements in the structure are repeated as long as a Boolean expression is true. The flow of logic keeps coming back up to the Boolean expression to check if it is still true. As soon as the Boolean expression is false, the flow of logic hops down to the end of the loop. Note the Boolean condition is also checked before the looping statements are executed the first time. This mean if the condition is not true the first time, the statements will never happen.

It is a common occurrence to have an accumulator or counter within a looping structure. The counter, usually, is incremented (1 is added) or decremented (1 is subtracted) each time the condition is met and the statements inside the loop are performed. When the counter reaches a certain number that is expressed inside the Boolean statement, then the Boolean expression becomes false and the loop is exited. Ensure you use proper style and DO NOT do what is very common in programming, just declare the variable as i, j or x. Always name a variable for what it is actually doing and holding. For example, if you are using a counter, name it counter or loopCounter. (Yes, I know “i” is short hand for iterator; just do not use it!)

The while loop (in most computer programming languages), takes the generic form of:

WHILE (Boolean expression)
statement(s)
counter = counter + 1
ENDWHILE

In this example program, the user is asked to enter a positive integer and the program will count how many times it goes through the loop until it reaches that number.

Top-Down Design for While loop

Top-Down Design for While loop

Flowchart for While loop

While loop flowchart

Pseudocode for While loop

GET positive_integer
WHILE (counter < positive_integer)
SHOW counter
counter = counter + 1
ENDWHILE

Code for While loop

Example Output

Code example output