while loop example in X++ Programming Language

Rumman Ansari   Software Engineer   2023-08-23   7865 Share
☰ Table of Contents

Table of Content:


A while loop is a type of loop statement in computer programming that allows a block of code to be executed repeatedly while a certain condition is true. The general syntax of a while loop is:

Syntax


i = initialValue; // Initialize loop control variable
while (i < endValue) {
// Loop body
...
i++; // Adjust loop control variable
}
 


While Loop Flow chart

A while loop in X++ iterates till its condition becomes False. In other words, it executes the block of statements until the condition it takes is true.

 X++While Loop Flow chart

Example


// while loop example

static void Examples(Args _args)
{ 
   int a = 1; // initialization part

    while(a <= 5 ) { // expresson part or conditional part
        info(strFmt(" %1 ",a));
        ++a;   // increment part
    }
}

This code demonstrates an example of a while loop in X++ programming language. Here's how the code works:

  1. The variable a is initialized to 1 using the assignment operator (=) in the first line of the method.

  2. The while loop is set up using the keyword while, followed by the condition that must be met for the loop to continue. In this case, the condition is a <= 5, which means that the loop will continue to execute as long as the value of a is less than or equal to 5.

  3. Inside the while loop block, the info() function is called with the value of a passed as an argument. This will display the value of a on the screen.

  4. After the info() function call, the variable a is incremented using the ++a syntax. This will add 1 to the value of a, so that on each iteration of the loop, the value of a increases by 1.

  5. Once a becomes greater than 5, the loop will exit, and the program control will continue after the while loop.

In this example, the while loop will execute 5 times, with the value of a printed to the console on each iteration. The output will be:


1
2
3
4
5

This code demonstrates how while loops can be used to repeat a block of code until a certain condition is met.


X++ Sample of while


static void JobRs002a_LoopsWhile(Args _args)
{
    int nLoops = 1;
    while (nLoops <= 88)
    {
        print nLoops;
        pause;
        // The X++ modulo operator is mod.
        if ((nLoops mod 4) == 0)
        {
            break;
        }
        ++ nLoops;
    }
    beep(); // Function.
    pause; // X++ keyword.
} 

Output:

The output in the X++ Print window is as follows:


1
2
3
4