ZetCode

F# for and while loops

last modified December 2, 2026

In this article we repeat code with the for and while loops of F#.

F# has three loops: for...to counts with an integer, for...in goes over the elements of a range, string or collection, and while...do repeats code while a condition holds. Functional F# code often replaces loops with recursion or with functions such as List.iter; those are covered in F# recursion and F# list. Loops are still the simplest way to repeat an action, and they are common in scripts.

The for...to loop

The for...to loop runs its body once for every integer from a start value to an end value, both included.

for_to.fsx
for i = 1 to 5 do
    printfn "Round %d" i

printfn "Done"

The loop prints five lines.

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

The loop variable i takes the values 1, 2, 3, 4 and 5. The body follows the do keyword and is an indented code block. The line that starts in the first column again runs after the loop.

λ dotnet fsi for_to.fsx
Round 1
Round 2
Round 3
Round 4
Round 5
Done

Counting down

To count from a larger value to a smaller one, we use downto instead of to. The bounds can be any integer expressions.

downto.fsx
let start = 5

for i = start downto 1 do
    printfn "%d..." i

printfn "Liftoff!"

let empty = 0

for i = 1 to empty do
    printfn "This line never runs"

printfn "The second loop ran zero times"

The first loop is a countdown. The second loop shows what happens when the end value is smaller than the start value.

for i = start downto 1 do

The start value comes from a variable. The loop counts 5, 4, 3, 2, 1.

for i = 1 to empty do

The loop counts up from 1 to 0. The body does not run at all; this is not an error.

λ dotnet fsi downto.fsx
5...
4...
3...
2...
1...
Liftoff!
The second loop ran zero times

The for...in loop with a range

The for...in loop takes its values from a sequence of values. The simplest sequence is a range, written as start .. end or start .. step .. end. Ranges are covered in detail in F# ranges.

for_in.fsx
for i in 1 .. 4 do
    printf "%d " i

printfn ""

for percent in 0 .. 25 .. 100 do
    printf "%d%% " percent

printfn ""

for i in 10 .. -3 .. 0 do
    printf "%d " i

printfn ""

Three loops go over three ranges. The printf function does not add a newline, so each loop prints one line; the empty printfn "" ends it.

for percent in 0 .. 25 .. 100 do

The middle value is the step. The range starts at 0 and goes up by 25 until it reaches 100.

for i in 10 .. -3 .. 0 do

A negative step counts down. The range stops at 1, because the next value, -2, would be past the end.

λ dotnet fsi for_in.fsx
1 2 3 4
0% 25% 50% 75% 100%
10 7 4 1

Looping over a string

A string is a sequence of characters, so for...in can go over it one character at a time.

chars.fsx
let word = "falcon"

for c in word do
    printf "%c " c

printfn ""

for c in word do
    printf "%c" (System.Char.ToUpper c)

printfn ""

The program prints the characters of a word separated by spaces, and then the word in capital letters.

for c in word do
    printf "%c " c

The loop variable c has the type char. Its type is inferred from the string; no index is needed.

printf "%c" (System.Char.ToUpper c)

The System.Char.ToUpper method of .NET returns the uppercase form of a character.

λ dotnet fsi chars.fsx
f a l c o n
FALCON

Accumulating a result

A loop often builds up a result: a sum, a count or a product. The result is stored in a variable declared with let mutable and updated with the <- operator, as shown in F# variables.

accumulate.fsx
let mutable sum = 0

for i in 1 .. 100 do
    sum <- sum + i

printfn "1 + 2 + ... + 100 = %d" sum

let mutable factorial = 1L

for i = 2 to 20 do
    factorial <- factorial * int64 i

printfn "20! = %d" factorial

let text = "the quick brown fox jumps over the lazy dog"
let mutable spaces = 0

for c in text do
    if c = ' ' then
        spaces <- spaces + 1

printfn "Words: %d" (spaces + 1)

The program computes a sum, a factorial and the number of words in a sentence.

let mutable factorial = 1L

for i = 2 to 20 do
    factorial <- factorial * int64 i

The value of 20! does not fit into an int, so the factorial is an int64. The loop variable is an int and is converted with int64 before the multiplication.

for c in text do
    if c = ' ' then
        spaces <- spaces + 1

The body of a loop is a block, and it can contain a conditional. Each space separates two words, so there is one word more than there are spaces.

λ dotnet fsi accumulate.fsx
1 + 2 + ... + 100 = 5050
20! = 2432902008176640000
Words: 9

Nested loops

A loop body can contain another loop. The inner loop runs completely for every value of the outer loop.

nested.fsx
let size = 6

printf "    "

for col = 1 to size do
    printf "%4d" col

printfn ""

for row = 1 to size do
    printf "%4d" row

    for col = 1 to size do
        printf "%4d" (row * col)

    printfn ""

for row = 1 to 4 do
    for _ in 1 .. row do
        printf "*"

    printfn ""

The first part prints a multiplication table with a header row and a header column. The second part prints a triangle of stars.

for row = 1 to size do
    printf "%4d" row

    for col = 1 to size do
        printf "%4d" (row * col)

    printfn ""

For every row, the inner loop prints six products. The %4d format pads each number to four characters, so the columns line up. The printfn "" line is part of the outer loop and ends each row.

for _ in 1 .. row do

The inner loop does not need its variable. The underscore tells the reader and the compiler that the value is not used.

λ dotnet fsi nested.fsx
       1   2   3   4   5   6
   1   1   2   3   4   5   6
   2   2   4   6   8  10  12
   3   3   6   9  12  15  18
   4   4   8  12  16  20  24
   5   5  10  15  20  25  30
   6   6  12  18  24  30  36
*
**
***
****

The while loop

The while loop repeats its body while a condition is true. It is used when the number of iterations is not known in advance. The condition usually depends on a mutable variable that the body changes.

while_loop.fsx
let deposit = 1000.0
let rate = 0.05

let mutable balance = deposit
let mutable years = 0

while balance < 2.0 * deposit do
    balance <- balance * (1.0 + rate)
    years <- years + 1

printfn "Deposit: %.2f" deposit
printfn "Interest rate: %.0f %%" (rate * 100.0)
printfn "The deposit doubles after %d years" years
printfn "Balance: %.2f" balance

The program finds out how many years it takes for a deposit to double at 5 percent interest.

while balance < 2.0 * deposit do
    balance <- balance * (1.0 + rate)
    years <- years + 1

The condition is checked before each iteration. Every iteration adds one year of interest and counts the year. When the balance reaches twice the deposit, the condition is false and the loop ends. If the condition is false from the start, the body never runs.

λ dotnet fsi while_loop.fsx
Deposit: 1000.00
Interest rate: 5 %
The deposit doubles after 15 years
Balance: 2078.93

Ending a loop early

F# has no break or continue statements. To stop a search when the answer is found, we put the stop condition into a while loop.

early_end.fsx
let text = "order 7734 shipped"

let mutable i = 0
let mutable found = false

while i < text.Length && not found do
    if System.Char.IsDigit text[i] then
        found <- true
    else
        i <- i + 1

if found then
    printfn "First digit '%c' at index %d" text[i] i
else
    printfn "No digit found"

The program looks for the first digit in a string.

while i < text.Length && not found do

The loop has two conditions: the index must stay inside the string, and the digit must not be found yet. The Length property gives the number of characters, and text[i] returns the character at index i, counted from zero.

if System.Char.IsDigit text[i] then
    found <- true
else
    i <- i + 1

When a digit is found, the flag is set and the index stays where it is. The next check of the condition ends the loop. In functional code, the same search is written with recursion or with a function such as Seq.tryFindIndex.

λ dotnet fsi early_end.fsx
First digit '7' at index 6

Loops return unit

Like if, a loop is an expression. Its value is (), the only value of the unit type. The body of a loop must have the type unit too; a body that computes a value gets a warning, because the value would be lost.

loop_unit.fsx
let result =
    for i in 1 .. 3 do
        printfn "Line %d" i

printfn "The loop returned %A" result

for i in 1 .. 3 do
    i * i

The first loop is bound to a name. The second loop computes squares but does nothing with them.

for i in 1 .. 3 do
    i * i

The compiler reports warning FS0020: the value of i * i is ignored. The fix is to use the value, for example to add it to a mutable sum, as in the section on accumulating a result. A warning does not stop the script, so the output follows it. The loop variable itself is immutable; assigning to it with i <- 5 fails with error FS0027.

λ dotnet fsi loop_unit.fsx
loop_unit.fsx(8,5): warning FS0020: The result of this expression has type 'int32' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'.

Line 1
Line 2
Line 3
The loop returned ()

Prime numbers

The last example puts the pieces together. It prints the prime numbers up to 50, with a for loop over the candidates and a while loop that tests the divisors.

primes.fsx
let limit = 50
let mutable count = 0

for n in 2 .. limit do
    let mutable divisor = 2
    let mutable isPrime = true

    while isPrime && divisor * divisor <= n do
        if n % divisor = 0 then
            isPrime <- false

        divisor <- divisor + 1

    if isPrime then
        printf "%d " n
        count <- count + 1

printfn ""
printfn "There are %d primes up to %d" count limit

A number is prime if no number from 2 to its square root divides it.

let mutable divisor = 2
let mutable isPrime = true

The two variables are local to the body of the outer loop, so they are created again for every candidate.

while isPrime && divisor * divisor <= n do

The inner loop stops at the first divisor, or when the divisor gets larger than the square root of n. Larger divisors need not be tested, because each of them would pair with a smaller one that was already found.

λ dotnet fsi primes.fsx
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
There are 15 primes up to 50

Source

F# language reference: Loops: for...to expression

F# language reference: Loops: for...in expression

F# language reference: Loops: while...do expression

In this article we have counted with for...to and downto, gone over ranges and strings with for...in, accumulated results, nested loops, repeated code with while, ended a search early and seen that loops return unit. Ranges are covered in F# ranges, and repetition without mutable variables in F# recursion.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.