while

Loops through the statements enclosed within the { code block } until the test_expression is false:

 

while (test_expression) {
statements ;
}

 

Compile & Run:

myVar is now: 0
myVar is now: 1
myVar is now: 2
myVar is now: 3
myVar is now: 4

 

*Note: interestingly, the compiler set the uninitialised myVar to 0.

However, this is bad programming practice and in reality should be defined.

 

Also note, it is possible to simply treat myVar as a boolean in the while test parentheses:

Compile & Run:

myVar is now: 5
myVar is now: 4
myVar is now: 3
myVar is now: 2
myVar is now: 1

 

 

Line 8  could have been written as while (myVar > 0) { but since it decrements to 0, and 0 is the same thing as FALSE, it is possible to simply treat myVar as a boolean in this case.

Leave a Reply