F# – for to and for downto

  • Post author:
  • Post category:F#
  • Post comments:2 Comments
F# - for...to and for...downto

F# for to and for downto is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax F# for to and for downto

The syntax of a for…to loop in F# programming language is −

for var = start-expr to end-expr do
   ... // loop body

The syntax of a for…downto loop in F# programming language is −

for var = start-expr downto end-expr do
   ... // loop body

Example 1

The following program prints out the numbers 1 – 20 −

let main() =
   for i = 1 to 20 do
      printfn "i: %i" i
main()

When you compile and execute the program, it yields the following output −

i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10
i: 11
i: 12
i: 13
i: 14
i: 15
i: 16
i: 17
i: 18
i: 19
i: 20

Example 2

The following program counts in reverse and prints out the numbers 20 – 1 −

let main() =
   for i = 20 downto 1 do
      printfn "i: %i" i
main()

When you compile and execute the program, it yields the following output −

i: 20
i: 19
i: 18
i: 17
i: 16
i: 15
i: 14
i: 13
i: 12
i: 11
i: 10
i: 9
i: 8
i: 7
i: 6
i: 5
i: 4
i: 3
i: 2
i: 1

Next Topic – Click Here

This Post Has 2 Comments

Leave a Reply