Thursday 2/24 Week 2

Chapter 2

Student Notes

 

Objectives:

Questions about project 1

Using Loops

Looking at an Exception

Using conditional statements

 

1.      Loops

·        Loops are a way to handle

·         

·        First loop we will look at is the

·         

·        FOR counterName IN StartNumber..EndNumber LOOP

.

.

.

loop body

.

.

.

END LOOP;

·        Can also          loops.

·         

·        FOR counter1 IN start1..end1 LOOP

       FOR counter2 IN start2..end2 LOOP

            Loop body;

       END LOOP;

  END LOOP;

·        FOR loops are also useful because

·         

·         

·        Example: Spiral

FOR Line IN 1..10 LOOP

  Spider.ChangeColor(NewColor => Spider.RandomColor);

  -- inner loop takes its bound from out count

 

  FOR Count IN 1..Line LOOP

    Spider.Step;

  END LOOP;

 

  Spider.TurnRight;

End LOOP;

 

1.      Dealing with an Exception

·        What is an exception?

·         

·        These exceptions can be generated by packages and programs

·        If we were to have the Spider walk 12 paces from its starting position, it would run into the wall. When this happens, our program crashes an we get an error which looks like this:

Raised SPIDER.HIT_THE_WALL

Traceback Information

  Program Name        File Name               Line

  ------------        ----------                  ----

  spider.step         spider.adb              264

  spider_crash        spider_crash.adb        16

 

1.      dealing with this exception in a more graceful way

·        The Spider package gives us a function called AtWall which will return a Boolean value when the Spider is next to the wall

·        Boolean value =

·         

·        FUNCTION AtWall RETURN Boolean;

-- pre: None

-- post: Returns True if the Spider is standing next to a wall.

·        Exception handling is a subject that we will spend a lot of time on later, however

·         

·         

·         

·        conditional statements

·        IF Spider.AtWall THEN

       EXIT;

     END IF;

·        What’s happening here?

·         

·         

·        Why can we just say Spider.AtWall?

 

 

 

2.      The General Loop

·        Structure:

LOOP

  IF Spider.AtWall THEN

    EXIT;

  END IF;

  Spider.Step;

END LOOP;

·        A Warning: Beware the infinite loop.

·         

·         

·        We would have to forcibly quit the program (^C)

·        Notice that we could have used a more concise wording of the IF statement by using the EXIT WHEN statement. This is very useful for loops.

·        LOOP

       EXIT WHEN Spider.AtWall;

       Spider.Step;

     END LOOP;