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.


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.


For loop


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:


Numbers from 1 to 5 will be printed in one time



Count Down For Loop


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


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

open System

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

for i =1 to 5 do
printfn "%d"i;;

 for i = 5 downto 1 do
 printfn "%d"i;;



Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now