– Branching [ if ]

We make decisions all the time. A lot of times this can be described as choosing which way to go when there is a fork in the road. Almost like choosing which part of the Y to go up. These can also be described like branches on a tree.

In programming, we make our branches out of “if” statements.

For example:

if (some_statement_is_true)

{

have_some_cool_things_happen;

}

Everything between the { and the } is all on one branch of the tree.

try this simple program:

int main()

{

while(!black_button())  /*to keep checking the A button until black button (or side button on Link) is pressed.*/

{

if(A_button()) /*if the A button is pressed the robot moves forward for 2 seconds */

{

motor(0,100);

motor(3,100);

msleep(2000);

}

ao(); /*if the A button is pressed it moves forward and stops, if not, the

motors are stopped anyway*/

}

}

Then you pair your if statement with an else statement.

Here’s a simple example:

int main()
 {
   int number=16; // variable declared as an integer, and initialized to 16
   if(number%2) /* the % operation finds the remainder, so if the number is 
   divisible by 2, the remainder will be 0, if not, then the remainder will be 1. 
   Remember from the Testing Statements section that any non-zero value is read 
   as true. */
      {
        printf("The number %d is odd",number); //you'll learn about printf() soon.
      }
  else
     {
      printf("The number %d is even", number);
     }
 }

So this program will check the remainder of a number when it is divided by two.  If it is odd, then it will have a remainder of one. This would make the if statement true and print out “The number 16 is odd.” Of course, when you divide 16 by 2 there is no remainder, so that will make the if statement false. So the program will execute the else statement or block and print out “The number 16 is even.”

Write this program into your KISS-C and you can either download it onto your robot, or just use the simulator.

NEXT: Loops

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s