Conditional Statements
Now that we have the ability to create Boolean expressions, we introduce conditional state-ments. A conditional statement allows a block of instruction to be executed depending
on the value of a Boolean expression.
5.3.1 If-statements
An if-statement is a block of instruction that is executed only if its predicate is true. The
predicate is the Boolean expression that controls whether or not the block of an if-statement
is executed. If the predicate is true, then the block will be executed, if it is false then the
block will be skipped and program execution will resume after the closing brace of the block.
The syntax, given in Listing 5.3 is simple and quite readable.
if( [ predicate ] ) {
// conditional block
}
Listing 5.3: The syntax of an if-statement. The predicate, a Boolean expression, determines
whether the succeeding block of instruction is executed.
5.3.2 If-else statements
A straightforward extension of the if-statement is the if-else-statement. In an if-else-statement
the value of the predicate determines which of two blocks of instructions is executed. The
syntax is summarized in Listing 5.4.
if( [ predicate ] ) {
// conditional block executed if
// the predicate is true
}
else {
// conditional block executed if
// the predicate is false
}
Listing 5.4: The syntax of an if-else-statement. If the predicate is true, the rst block is
executed, otherwise the second block is executed.
More on the if-else statement can be found here2.
In Listing 5.5, we test the value of the sonar sensor and display dierent messages de-
pending on the distance measured by the sensor at run time.
# pragma config ( Sensor , S1 , Sonar , sensorSONAR )
task main () {
int distance = 0;
distance = SensorValue [ Sonar ];
nxtDisplayString (3," Sonar : %d", distance );
if ( distance > 50) {
nxtDisplayString (4," Come closer ,");
nxtDisplayString (5," I can 't see you!");
}
else {
nxtDisplayString (4," Back off man!,");
}
wait10Msec (300);
}
Listing 5.5: An example of an if-else-statement. If the distance measured by the sonar is
greater than 50cm, then the rst message is displayed. If it is less than or equal to 50cm,
then the second message is displayed. The instruction at the top \declares" the sonar sensor
and was inserted by RobotC.
The current value of the sensor is an integer and is always available in SensorValue[Sonar]
(this is actually an array element, we will discuss arrays a little later). For convenience and
readability, we copy the current value of the sonar sensor into the integer-type variable,
distance. For the sake of the example, we arbitrarily decide that if the sonar reading is
more than 50cm, then the target is too far away and if it is less than or equal to 50cm, then
it is too close. We use the if-else-statement to display dierent messages depending on this
condition. The predicate in this case is (distance>50). The value of the predicate depends
on the value of the indeterminate, distance.
No comments:
Post a Comment