Section 5.1 Making Decisions in Code There are three ways to control how a program runs. The first is called sequence. Sequence means that the program will perform the first line of e code first. Then it will continue to the second line of code, then the third line, and so on. The computer does not skip around. The second method of controlling a program is called selection. Selection means that a computer program can make decisions on which lines of code to execute. The program can look at the results of an event or calculation. It can then decide what to do next. For example, if a sprite is moving across the stage and it comes to the edge, the script can decide what the sprite should do. Will it disappear, come back in on the other side, or bounce back and head in the opposite direction? The coder programs these decisions into the script. If a teacher is averaging test scores for a student, the program can decide what letter grade to assign based on the numerical average. If a user is playing a game, the program can keep track of the score or the number of attempts. Then, the program can decide when the game is over. The third method of control is called repetition. Previous chapters introduced this control. It is explored in more detail in the next chapter. In Scratch, IF…THEN and IF…THEN…ELSE blocks are used to make decisions and control actions in programs. When a program runs, it evaluates expressions. If an expression is true, a specific set of instructions is performed. If false, a different set of instructions is performed. See Figure 5-1. The standard format for an IF…THEN statement is: IF expression is true THEN action to perform The standard format for an IF…THEN…ELSE statement is: IF expression is true THEN action to perform ELSE other action to perform IF the ball hits a wall, THEN bounce ELSE keep rolling. IF it is dark, THEN turn on the light. IF it is dark, THEN turn on the light. IF IF the th e ball ba ll hits h it s a a wall, wa ll THEN TH EN bounce bo un ce ELSE EL SE keep ke ep rolling. r ol li ng Goodheart-Willcox Publisher Figure 5-1. The IF…THEN and IF…THEN…ELSE statements form the basis of actions and reactions in computer programming. Copyright Goodheart-Willcox Co., Inc. 100 Introduction to Computer Science: Coding
Previous Page Next Page