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 body
.
.
.
END
·
Can also loops.
·
·
FOR
counter1 IN start1..end1
FOR
counter2 IN start2..end2
END
END
·
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
Spider.TurnRight;
End
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:
IF Spider.AtWall THEN
EXIT;
END IF;
Spider.Step;
END
·
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.
·
EXIT WHEN Spider.AtWall;
Spider.Step;
END