What is the OCaml while loop?
OCaml, also known as Objective Caml, is a high-level general-purpose programming language. It is a combination of functional and
In this Answer, we will discuss the OCaml while loop in detail.
The while loop
A while loop executes a code block until a condition is true. The while loop condition is checked before executing the defined code block. When we enter a while loop, the defined condition is checked. If the condition is true, then the code block is executed. Otherwise, the while loop breaks if the condition is evaluated as false.
The illustration below shows that the condition is checked before executing the code block when we enter the while loop. If the condition is false, the while loop breaks, and the code block is not executed. In the case of a true condition, the code will execute and check the while condition again for the next iteration. This process continues until the condition becomes false.
Syntax
The syntax of the while loop is given below:
while condition do# Execute Code blockdone
It checks the condition and then goes through the loop’s body based on whether it is true or false.
Code example
Let’s go through an example of a while loop in OCaml where we have to print numbers from to .
let current_number = ref 1 inwhile !current_number <= 10 doprint_string "The number is: ";print_int !current_number;print_newline ();current_number := !current_number + 1done;;
Code explanation
In the code above:
-
Line 1: The code defines a reference variable,
current_number, to check the condition of the loop. -
Line 2: The code goes through the
conditionof the loop and checks ifcurrent_number <= 10. -
Lines 3–5: The code prints the
current_numberand new line. -
Line 6: The code updates the value of
current_numberby1. -
Line 7: The statement
doneshows that thewhileloop ends here.
Free Resources