C Handout 5 
Blocks and Conditional Execution

(10/10/00 - Page 3)

 

Blocks

A C-statement-block is either a single line, or one or more lines enclosed in an opening brace, {, and ending with a closing brace, }.  Each line must be terminated with a semi-colon.

 

If…then…else

Up until now we have had programs that executed the same series of steps, no matter what.  For a program to demonstrate some intelligence, it needs to be able to make choices.   However, we will predestine what the processor will do with each choice.  To make choices we will use an if…then…else construct.

 

If…then

The simplest form of the construct is simply an if…then clause.

if (logical-expression) C-statement-block

 

In this construct the C-statement-block only gets executed if the logical expression is TRUE.   Let’s give two examples.  The first uses the SetSpeed function of the previous worksheet.

            if (digital(7) && digital(8)) SetSpeed(100,100);

In this example both bumper are not depressed, the speed of both motors is set to 100.  We could also do this without the function call using a multi-line C-statement-block.

                      if (digital(7) && digital(8)) {

motor(0,100); /*Set both motors to 100%*/

motor(1,100);

}

 

 

If…then…else

A slightly more complicated type of decision making can be accomplished with an if…then…else construct

if (logical-expression) C-statement-block#1

else C-statement-block#2

 

In this construct C-statement-block#1 gets executed if the logical expression is TRUE, and C-statement-block#2 gets executed if the logical-expression is FALSE. 

/*If analog(0)>analog(3)) then there is more light on the right

  side of the robot (the voltage is lower).  In this case, make

  the right motor, 1, turn  slower than the left motor – turning

  the robot towards the light.  In the other case, turn toward

  the left, where the bright light is.

     */ 

if (analog(0)>analog(3)) {

motor (0,100);

motor (1,50);

} else {

motor(0,50);

motor(1,100);

}

We could just as easily have done the same thing with function calls.

if (analog(0)>analog(3)) SetSpeed(100,50);

      else SetSpeed(50,100);

 

Review Sheet – Blocks and Conditional Execution

 

Fill in the blanks to show the values of i and j as the program executes.

 

void main() {

int i,j;

 

i=0;

j=3;

/*i=_______________, j=_____________*/

 

if (i<j)

      i=j+1;

else

      i=0;

/*i=_______________, j=_____________*/

 

 

if (i<j)

      i=j+1;

else

      i=0;

/*i=_______________, j=_____________*/

 

 

i=0;

j=3;

 

if (i==j) j=4;

/*i=_______________, j=_____________*/

 

 

if (i=j) j=4

/*i=_______________, j=_____________*/

 

 

i=0;

j=3;

 

if (i==!j) {

j++;

i++;

} else {

i—-;

j--;

}

/*i=_______________, j=_____________*/

 

}