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 imperativeIn imperative programming, functions contain explicit instructions detailing each step needed to solve a problem. programming. Ocaml is known for its strong type system, type inferenceAutomatic detection of the type of an expression in a formal language, and support for functional programming concepts.

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.

The while loop flow
The while loop flow

Syntax

The syntax of the while loop is given below:

while condition do
# Execute Code block
done

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 11 to 1010.

let current_number = ref 1 in
while !current_number <= 10 do
print_string "The number is: ";
print_int !current_number;
print_newline ();
current_number := !current_number + 1
done;;

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 condition of the loop and checks if current_number <= 10.

  • Lines 3–5: The code prints the current_number and new line.

  • Line 6: The code updates the value of current_number by 1.

  • Line 7: The statement done shows that the while loop ends here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved