Home

Looping While a Condition is Verified

   

Introduction

Instead of counting from a starting value to a known end, you may want to execute a statement from a begining value but continue as long as a certain condition exists; The condition can be true or false, as long as it is verified as such. This is done using the while keyword. The formula to follow is:

while Condition do
    body

The while and the do keywords are required. The Condition is something that needs to be checked. It could be a conditional operation or anything that can produce a true or false result. After the do keyword, create a body for the loop. Here is an example:

open System
open System.Windows.Forms

let exercise = new Form()
exercise.Text   <- "Numbers"
exercise.Width  <- 135
exercise.Height <- 160

let lbxNumbers = new ListBox()
lbxNumbers.Left   <- 21
lbxNumbers.Top    <- 12
lbxNumbers.Width  <-  80
lbxNumbers.Height <- 100

let mutable number = 12

while number <= 24 do
    lbxNumbers.Items.Add(string number) |> ignore
    number <- number + 2

exercise.Controls.Add lbxNumbers

do Application.Run exercise

This would produce:

Looping While a Value Exists

     
     
 

Home Copyright © 2015 FunctionX Home