LSP- While Statements Lesson

While Statements

Repetition allows programs a way to repeat behavior such as drawing multiple shapes.  

Look at the example below. A rectangle is repeated three times by increasing the value of x by 30 pixels each time.  

This code would be sufficient if we wanted to just draw three rectangles but it would not be the best scalable solution. What if we wanted to draw 20 rectangles or 100 rectangles? Each line of code for the rectangle function would have to be written individually for each rectangle drawn.    

A while loop would be a better solution. A while loop is a conditional loop. A conditional loop executes based on a condition. It uses a boolean expression as the condition to execute the loop. While the condition is true, the loop will continue. When the condition becomes false, the loop will stop.

Basic syntax:

while ( condition) {

}

There are three basic parts to a loop structure:

  • Initializing variable - this variable will set the initial value when the loop starts.      
  • Condition - is a boolean expression whose value dictates when the looping terminates - so long as condition is true, the loop continues; when condition becomes false, the loop stops.  
  • Step: increment/decrement - the initializing variable must be changed for the loop to work properly.   This will increase or decrease the initializing variable by a certain amount each time through the loop working in the direction of making the boolean expression become false.

In the while loop example, the counter is the initializing variable. It is set to 0. The initialize variable is then used in the condition to control when the loop stops. The condition is counter < 10. The body of the loop starts with a curly brace. Inside the body the rectangle is drawn. The variable x is an accumulator and is increased by 30 each time through the loop. This changes the x location of the rectangle each time through the loop. The counter is then incremented by one using the ++ operator. The number of rectangles produced is based on the condition.        

Let's trace through the code to see what happens each time through the loop.   

In the while loop example, the counter is the initializing variable. It is set to 0.  

You can also decrement or decrease the initializing variable using the -- short-cut operator. When you do this you must change the sign in the condition.  

Syntax with a while statement:

  1. The word while is lowercased.
  2. The condition is in parentheses.
  3. The body of the while loop is enclosed in curly braces.
  4. Never put a semicolon after the while condition. It will not execute.

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION