while loop example in X++ Programming Language
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.
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:
-
The variable
a
is initialized to 1 using the assignment operator (=) in the first line of the method. -
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 isa <= 5
, which means that the loop will continue to execute as long as the value ofa
is less than or equal to 5. -
Inside the while loop block, the
info()
function is called with the value ofa
passed as an argument. This will display the value ofa
on the screen. -
After the
info()
function call, the variablea
is incremented using the++a
syntax. This will add 1 to the value ofa
, so that on each iteration of the loop, the value ofa
increases by 1. -
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