2018-12-30 16:43:04 -08:00
|
|
|
---
|
|
|
|
|
title: constructs / while
|
|
|
|
|
---
|
2023-11-25 09:50:24 -08:00
|
|
|
# while
|
2018-12-30 16:43:04 -08:00
|
|
|
|
2020-03-11 23:17:48 +08:00
|
|
|
### The LPC while loop:
|
1993-01-07 13:20:58 -05:00
|
|
|
|
2018-12-30 16:59:01 -08:00
|
|
|
LPC's while loop is identical to that provided by C. Syntax is as follows:
|
1993-01-07 13:20:58 -05:00
|
|
|
|
2020-03-11 23:17:48 +08:00
|
|
|
while (expression)
|
|
|
|
|
statement;
|
1993-01-07 13:20:58 -05:00
|
|
|
|
|
|
|
|
where statement may be replaced by a block of statements delimited by
|
2018-12-30 16:59:01 -08:00
|
|
|
matching curly brackets. For example:
|
1993-01-07 13:20:58 -05:00
|
|
|
|
2020-03-11 23:17:48 +08:00
|
|
|
while (expression) {
|
|
|
|
|
statement0;
|
|
|
|
|
statement1;
|
|
|
|
|
}
|
1993-01-07 13:20:58 -05:00
|
|
|
|
|
|
|
|
The statements inside the body of the while loop will be executed
|
|
|
|
|
repeatedly for as long as the test expression evaluates to non-zero.
|
|
|
|
|
If the test expression is zero just prior to the execution of the loop,
|
2018-12-30 16:59:01 -08:00
|
|
|
then the body of the loop will not be executed. A 'break;' statement
|
1993-01-07 13:20:58 -05:00
|
|
|
in the body of the loop will terminate the loop (skipping any statements
|
2018-12-30 16:59:01 -08:00
|
|
|
in the loop that remain to be executed). A 'continue;' statement
|
1993-01-07 13:20:58 -05:00
|
|
|
in the body of the loop will continue the execution from the beginning
|
|
|
|
|
of the loop (skipping the remainder of the statements in the loop for
|
|
|
|
|
the current iteration).
|
|
|
|
|
|
2020-03-11 23:17:48 +08:00
|
|
|
```c
|
1993-01-07 13:20:58 -05:00
|
|
|
int test(int limit)
|
|
|
|
|
{
|
2020-03-11 23:17:48 +08:00
|
|
|
int total = 0;
|
|
|
|
|
int j = 0;
|
|
|
|
|
while (j < limit) {
|
|
|
|
|
j++;
|
|
|
|
|
if ((j % 2) != 0)
|
|
|
|
|
continue;
|
|
|
|
|
else
|
|
|
|
|
total += j;
|
|
|
|
|
}
|
|
|
|
|
return total;
|
1993-01-07 13:20:58 -05:00
|
|
|
}
|
2020-03-11 23:17:48 +08:00
|
|
|
```
|
1993-01-07 13:20:58 -05:00
|
|
|
|
|
|
|
|
The results of this code fragment will be to sum all of the even numbers
|
2018-12-30 16:59:01 -08:00
|
|
|
from 0 to to limit - 1.
|