For and While Loop in F#


Introduction: The looping concept is introduced in programming to repeatedly execute several lines of code for specific numbers of time. Generally lines of code execute one-by-one, meaning one line then another line then another and so on. When we need to execute a specific line of codes repeatedly for a certain time, then we can use looping concept. Loops are also referred as repetition or iteration. Now, we try to understand looping concepts in FSharp. We start with a simple While loop.

while Loop: The body of while loop is executed until given the conditional expression evaluates to false. At first, the given condition is evaluated, if the  condition is true then the body of the loop is executed then again the condition is evaluated. This process continues till  condition is true. Its syntax is given below

   while condition_exp do
         
body of loop

Write the following code in a F# application.
 
//while loop

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

Run the application, the output will look like below:

while loop in f#

For Loop: We use a for loop when there is a need to execute several lines of code for a fixed number of times.

Simple For Loop: In a simple for loop, the start and end value is specified. The body of the for loop is iterated till the counter is less than the end value. Its syntax is given below

   for identifier=start_value to/downto end_value do
                     body of for loop

We write the following code.

//simple for loop using to

for i=1 to 10 do
printfn "  %d" i

Run the application, the output will look like below:
 
simple for loop in f#

We write the following code.

//simple for loop using downto

for
i=10 downto 1 do
printfn "  %d" i

The output will look like the below figure:

for loop using downto

For Loop With Collections: In F#, a for loop is also used with collections. It acts the same as foreach  in C#. Its syntax is given below

   for pattern in Exp do
           body of loop


For Loop with List:      
                         

//for loop with list

let
simplelist=[2;4;6;8;10]
for
i in simplelist do
printfn " %d" i

The output will look like as below figure:

for loop with list

For Loop With Array:

//for loop with array
let
arr=[|1;2;3;4;5|]
for
i in arr do
printfn " %d" i

The output will look like below:

for loop with array in f#

For Loop With Integer Range:

//for loop with integer range
for
i in 1..5 do
printfn " %d" i

The output will look like below:

for loop with range

For Loop With character Range:

//for loop with character range

for
i in 'a'..'e' do
printfn " %c" i

Output will look like below:

for loop with character range


Similar Articles