Introduction to Algorithms/Flow Control

This is a lesson in in the course, Introduction to Algorithms, which is a part of The School of Computer Science

Objective

edit


Flow Control

edit

Our current toast making algorithm works well if you are making toast for yourself, but what if you have a few friends around for breakfast and you need to make them toast as well? The algorithm clearly needs to be improved so that we can make toast for everyone. Also, simply waiting for the toasted is very boring, we could be doing something else while we wait. The third problem with making toast for friends is that they are fussy, what if some of them want butter whilest others prefer margarine, or even just plain toast

Algorithm for making buttered toast (4.0)

 LET A = a loaf of bread
 LET T = a toaster
 LET P = a plate
 LET B = some butter
 LET M = some margarine
 
 FOR every friend (F) eating toast{
   LET S = cut slice from A
   move S to T
   turn on T
   WHILE T is not finished{
     talk to F
   }
   move S to P
   
   IF F likes B{
     LET X = B
   }ELSEIF F likes M{
     LET X = M
   }ELSE{
     LET X = NOTHING
   }
   spread S with X
   move P to F
 }

As can be seen, to resolve the three problems above, I had to implement the three main types of flow control, a For Loop, a While Loop and an If Statement. It should be obvious from the example what each of these does. I also involved a new variable X, which unlike the variables I have used before changes its value as the algorithm progresses.

Assignments

edit

Completion status: this resource is a stub, which means that pretty much nothing has been done yet.