130 likes | 238 Vues
This guide delves into the If-Then-Else instruction used in Karel the Robot programming. It outlines how the format works and the significance of reserved words like IF, THEN, and ELSE in controlling program flow. The piece further explains nested if statements for complex tests, and how to write efficient conditional statements by factoring out redundant instructions. Through examples, we learn to create clearer, more efficient, and error-free code, enhancing both readability and runtime performance.
E N D
CSE 111 Karel the Robot
If Then Else Instruction • Format If condition THEN BEGIN instruction(s) END ELSE BEGIN instruction(s) END; • How does it work? • If condition is met, then perform instructions in THEN clause • If not, perform instructions in ELSE clause
If Then Else Instruction • Reserved Words • IF • THEN • ELSE • Test Conditions • Same as if/then instruction
If Then Else Instruction • As with the if/then instruction, any number of instructions can be placed between the delimiters BEGIN & END
If Then Else Instruction • Notice how the semicolon after END indicates the end of the if/then/else statement • If/then • Semicolon after END • If/then/else • Semicolon after second END!
If Then Else Instruction • Example IFnext-to-a-beeperTHEN BEGIN pickbeeper; END ELSE BEGIN putbeeper; END;
Nested If Statements • If/then or if/then/else statements written within the then or else clause of another instruction • Used for more complex tests • Avoid nesting more than one level deep to keep programs readable
Nested If Statements • Example • Task • Pick up two beepers • Ensure that if there are not two beepers on the intersection Karel is standing on, the program will NOT end in an error shutoff • Code IFnext-to-a-beeperTHEN BEGIN pickbeeper; IFnext-to-a-beeperTHEN BEGIN pickbeeper; END END;
Writing Efficient Conditional Statements • Factoring • Programs can be made more readable by removing redundant instructions from inside a conditional statement to outside the statement • It also reduces size of program • Can lead to faster runtimes since memory accesses are reduced • Example #1 • The following code fragment can be factored IFnext-to-a-beeperTHEN BEGIN pickbeeper; move; END ELSE BEGIN putbeeper; move; END;
Writing Efficient Conditional Statements • Factoring • Example #1 • After factoring IFnext-to-a-beeperTHEN BEGIN pickbeeper; END ELSE BEGIN putbeeper; END; move;
Writing Efficient Conditional Statements • Factoring • Example #2 • The following code fragment can be factored IFnext-to-a-beeperTHEN BEGIN pickbeeper; turnleft; END ELSE BEGIN pickbeeper; move; END;
Writing Efficient Conditional Statements • Factoring • Example #2 • After factoring pickbeeper; IFnext-to-a-beeperTHEN BEGIN turnleft; END ELSE BEGIN move; END;
References • Richard E. Pattis (revised by Jim Roberts & Mark Stehlik), Karel the Robot, John Wiley & Sons, Inc., 2nd edition, 1995, pp 65-86