2 RepetitionIn some situations, we don’t know exactly how many times a block of instructions should be repeated.All we know is that repetition is neededFor example, in a board game like chess or checkers, we don’t know exactly how many moves it will take for a player to win or lose the game – all we know is that several moves will be needed.
3 Indefinite Repetition In programs where a count of repetitions is not known (indefinite), we can use one of two repetition control mechanisms:RecursionWhile statementThis session focuses on Recursion.
4 RecursionMany of the pieces we use to create a program are identified by using special words. For example,Do in orderDo togetherIf/ElseLoopRecursion is not a program statement with a special word that identifies it as part of the programming language.Recursion means that a method (or a question) calls itself.
5 Example – horse race A carnival style horse race. In repeated moves, one horse is randomly selected to move forward. The selected horse “runs” straight ahead to the finish line.A horse is the winner if it gets to the finish line before any other horse. When one horse wins, the game ends.
6 Storyboard"do everything again" means that the entire method should be repeated – this is where recursion occurs.raceIf one of the horses has wonthe winner says, “I won!!!”Elserandomly choose one horse and move it forward a small amountdo everything again
7 Question How do we implement “do everything again” ? Create a call to the race method itself.Recursion means that a method calls itself.raceIf one of the horses has wonthe winner says, “I won!!!”Elserandomly choose one horse and move it forward a small amountcall the race method
8 Stepwise Refinement race If one of the horses has won the winner says, “I won!!!”Elserandomly choose one horse and move it forward a small amountcall the race methodmoveRandomHorseForwardwhichHorseWon?isGameOver?
9 isGameOver To determine whether the game is over, ask the question: Is the finish line < 0.5 meters (arbitrary distance) in front of a horse?
10 moveRandomHorseForward To randomly choose a horse and move it forward, use the built-in random selection question.
11 whichHorseWon To determine the winner, we ask the question: "Which horse is within 0.5 meters of the finish line?"
12 Putting together the pieces Recursive call.Note: The winning horse says "I won!!!"-- a lame ending, we know.
14 TestingTesting a program that used random numbers requires extra caution.In this example, we ran the program 20 times and found thatracehorse1 won 7 timesracehorse2 won 3 timesracehorse3 won 10 timesSomething is wrong! Each horse should win approximately 1/3 of the time.
15 Removing the bug The bug in this code is that we have nested If statements, andwe used a 33% probability for each If statementWhat we didn't consider is that if racehorse1 was not selected, then we have a 50% probability of selecting either racehorse2 or racehorse3.
16 Revised moveRandomHorseForward The corrected code: