How to use the for loop in Ocaml

Overview

The for loop is used to execute a code block over a given amount of time. This loop is very useful in Ocaml or other programming languages.

Syntax

for var = initial_value to final_value do
expression
done
Syntax of for loop in Ocaml

Code example

Let's look at the code below:

for i = 1 to 10 do
print_int(i)
done;;

Explanation

In the above code, we use the for loop to print all the numbers from 1-10.

  • Line 1: We start the for loop and define the range for the loop i = 1 to 10. The loop stops once i reaches 10. After the do keyword, we put the code block we want to execute while the loop is running.
  • Line 2: We use the done keyword to stop the for loop.

Free Resources