Algorithms
An algorithm is an effective method expressed as a finite list of well- defined instructions for accomplishing a goal.. Have one student give instructions to a mentor for how to make a peanut butter and honey sandwich. What things aren’t perfectly clear?
Sequential execution The normal order of statement execution is sequential – first statements first. Open the bag of bread. Remove two slices of bread Reclose the bag of bread. Open the peanut butter Using a knife, Spread peanut butter on one slice of bread Using a knife, Spread honey on the other piece of bread. Put the two pieces of bread together with gooey sides together Eat it!
If-then-else An IF-THEN-ELSE statement if a way of describing choices. IF (boolean condition) THEN (consequent) ELSE (alternative) END IF We use if-then-else statements in everyday life. Example: If you finish your homework, you can play on the computer else you cannot.
We can “nest” if-then-else instructions If you have done your homework if you have exercised you may play video games else exercise you need to do your homework.
Another way of saying something similar If you haven’t done your homework do your homework else if you haven’t exercised exercise else if you want to play video games play video games.
While statement Another way of controlling the order of instructions is with a while statement. We use a while statement in everyday life. Example: while your teeth are dirty, brush Example: while you aren’t finished with the lawn, mow Example: while the bread isn’t covered with peanut butter, get more peanut butter on the knife and spread it.
If this activity, we’ll use an algorithm to teach the computer how to play tic-tac-toe Look for if-then-else constructs Are there any while constructs?
Tic Tac Toe Algorithm I am X… and I go first… Move 1: Go in a corner. Move 2: IF the other player did not go in the opposite corner (from where you played) THEN go there ELSE go in a free corner. Move 3: IF there are 2 Xs and a space in a line THEN go in that space. ELSE IF there are 2 Os and a space in a line THEN go in that space. ELSE go in a free corner. Move 4: IF there are 2 Xs and a space in a line THEN go in that space. Move 5: Go in the free space.
Another way of stating the algorithm while not (game over){ increment move make appropriate move (from previous slide) } Game Over is true when there are three X’s in a row (X wins) there are three O’s ins a row (O wins) there are no more spaces left (it is a tie)