dowhile statement

The dowhile loop is a control structure in Tipcontrol and slightly different to languages, such as C++,it is used to execute a block of code at least once and then repeat the execution as long as a specified condition evaluates to true. This structure guarantees at least one iteration, as the condition is checked after the loop body is executed. The difference to C an similiar languages is that the condition is written at the top of the control block dowhile(…) instead of after, even though the test is done after the execution.

Structure of a do...while Loop

Components:

  1. Condition: An expression evaluated aafter each iteration of the loop. If the condition evaluates to true (non-zero), the code block inside the loop is executed again. If it evaluates to false (zero), the loop terminates.
  2. Code Block: The block of code that executes during each iteration while the condition is true. This block is enclosed in curly braces {}.

Simple Example

    counter = 1; // Initialization

    // Loop while counter is less than or equal to 5

    dowhile (counter < 1) {

        lib.log(“Count: “+ counter);

        counter+=1; // Update the counter

    }

Explanation:

  • Initializationcounter = 1; initializes a counter variable.
  • Conditioncounter < 1 checks if the counter is less than or equal to 1, the loop in the example will run once as the condition is only checked after the code block. 
  • Code Block: The statement lib.log(“Count: “ + counter); is executed at least once, and then as long as the condition is true.
  • Updatecounter+= 1 increments the counter at the end of each iteration to eventually make the condition false and terminate the loop.

Practical Use

The dowhile loop is particularly useful when you need a loop to execute the code block at least once, regardless of whether the condition is initially true or false, for example reading values from a sensor or other operations that need an initial value.