Loops in F#


In this article we will explore loops in F#.

Start visual studio. Create a new project and from Visual F# tab select F# Application project type.

image1.gif

All the basic working of loops is exactly the same as it works in other languages.

While Loop

While loops until Boolean predicate value evaluates to false.

There are two points to note while working with while loops:

  1. Condition must evaluate to loop
  2. Body must evaluate to unit.

    image2.gif

For loop

image3.gif

Now when we run this, numbers from 1 to 5 will be printed one by one. What I mean here is that since there is only one semicolon, after printing of each number we need to press Enter.

Now if we modify the preceding code as:

image4.gif

Numbers from 1 to 5 will be printed in one time

Output

image5.gif

Count Down For Loop

image6.gif

downto keyword is used to iterate from upper limit to lower limit.

image7.gif

// Learn more about F# at http://fsharp.net

open System
[<EntryPoint>]

let mutable i = 0
while i < 5 do
    i <- i+1
    printfn "%d" i;;

for i =1 to 5 do
printfn "%d"i;;
System.Console.ReadKey();

 for i = 5 downto 1 do
 printfn "%d"i;;
 System.Console.ReadKey();