Download presentation
Presentation is loading. Please wait.
1
CSE 111 Karel the Robot
2
If Then Else Instruction
Format If condition THEN BEGIN instruction(s) END ELSE END; How does it work? If condition is met, then perform instructions in THEN clause If not, perform instructions in ELSE clause
3
If Then Else Instruction
Reserved Words IF THEN ELSE Test Conditions Same as if/then instruction
4
If Then Else Instruction
As with the if/then instruction, any number of instructions can be placed between the delimiters BEGIN & END
5
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!
6
If Then Else Instruction
Example IF next-to-a-beeper THEN BEGIN pickbeeper; END ELSE putbeeper; END;
7
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
8
Nested If Statements Example Task Code 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 IF next-to-a-beeper THEN BEGIN pickbeeper; END END;
9
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 IF next-to-a-beeper THEN BEGIN pickbeeper; move; END ELSE putbeeper; END;
10
Writing Efficient Conditional Statements
Factoring Example #1 After factoring IF next-to-a-beeper THEN BEGIN pickbeeper; END ELSE putbeeper; END; move;
11
Writing Efficient Conditional Statements
Factoring Example #2 The following code fragment can be factored IF next-to-a-beeper THEN BEGIN pickbeeper; turnleft; END ELSE move; END;
12
Writing Efficient Conditional Statements
Factoring Example #2 After factoring pickbeeper; IF next-to-a-beeper THEN BEGIN turnleft; END ELSE move; END;
13
References Richard E. Pattis (revised by Jim Roberts & Mark Stehlik), Karel the Robot, John Wiley & Sons, Inc., 2nd edition, 1995, pp 65-86
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.