Break statements
In addition to the predicate becoming false, a second method of ending a while-loop is thebreak statement. If, during the execution of the while-loop body block, a break state-
ment is encountered, the program execution immediately jumps to the rst instruction after
the while-loop block{eectively terminating the while-loop. Typically, the break statement
should be enclosed in some kind of if-statement. Otherwise, the loop will end on its rst
iteration.
It is important to note, in the case of nested loops, that the break statement only termi-
nates the inner-most enclosing loop, while outer loops may continue. A break statement is
useful if one, or more, conditions arise during the execution of the loop making it necessary
to terminate the loop immediately. An example of this is in Listing 6.5. Similar to Listing
6.4, the main loop in Listing 6.5 terminates when the count reaches 20. We accomplish this
by inserting an if-statement immediately following the increment of the count variable. Only
when the value of count is 20 will the break statement be executed. This would be useful
if we were designing a devices that measured how quickly someone could tap the trigger 20
times.
# pragma config ( Sensor , S1 , trigger , sensorTouch )
task main () {
int count =0;
nxtDisplayCenteredBigTextLine (3,"%d",count );
while (1) {
// hold as long as trigger is not depressed
while (!( SensorValue [ trigger ])) {}
// increment the trigger count by 1
count ++;
if ( count == 20) { break ; }
// hold as long as trigger is depressed
while (( SensorValue [ trigger ])) {}
// reset display and display the current
count eraseDisplay ();
nxtDisplayCenteredBigTextLine (3,"%d",count );
}
count eraseDisplay ();
nxtDisplayCenteredBigTextLine (1,"20 Taps Reached ");
nxtDisplayCenteredBigTextLine (5," Exiting ");
wait10Msec (300);
}
Listing 6.5: This program will count the number of times the tough sensor has been depressed
and released and display the count on the screen. When the threshold count of 20 is reached
the program exits with an exit message.
Notice that we added a few lines of instruction after the while-loop in order to display
an exit message indicating that the 20 threshold has been reached.
No comments:
Post a Comment