Decision Structures Chapter 4 Part 1 Chapter 4 Objectives To understand o o o o o What values can be stored in a Boolean variable What sequence structures are What are decision structures The difference between dual-alternative and singlealternative decision structures Nested instructions 4-2 Boolean Variables Boolean Variables hold only two values o o o True False Initial Value is usually set to be “TRUE” How it looks in variable definitions 4-3 Boolean Functions Boolean Functions return one value from one of following o o Example: Ask user for yes or no o True False User prompted to answer Yes (true) or No (false) Asks the following question: 4-4 If/Else Decision Structure All previous instructions have been consecutively executed One After The Other If/Else checks a Boolean condition then makes a decision o If condition is True: one set of instructions are executed False: a different set of instructions is executed 4-5 If/Else Flow Chart Flow charts help to visually see which instruction sequence will be used next 4-6 Algorithm For Conditional Statement BOTH actions will NOT be performed…only ONE can be! If the hole is wider than the penguin penguin falls down the hole Else penguin says “Drats!” End If TRUE FALSE The penguin falling or speaking are instructions that are conditionally executed o o They do NOT always execute Executed only under certain conditions 4-7 If/Else Flowchart Compared to Alice Penguin falls down into the hole 4-8 If/Else Statement Location Drag If/Else tile to Do Nothing If/Else Tile 4-9 Using If/Else Instruction Empty If/Else instruction Two empty “slots” in instruction o If part o Else part After dragging If/Else instruction to location choose true or false as placeholder Replace placeholder with Boolean variable, Boolean function, relational operator or logical operator Add instructions to If and Else parts More than one instruction can be added to If and Else parts 4-10 Single-Alternative Decision Structures If/Else is a dual-alternative decision structure o There are two paths of execution One when If condition is TRUE Other when If condition is FALSE Single-alternative decision structures are similar to dual-alternative o o Decides whether instructions in If path should be executed or not Else part is empty therefore nothing is executed 4-11 Single-Alternative Decision Structure Start Penguin turns to face hole Hole wider than penguin? False True Penguin walks to center of hole Penguin falls into hole End 4-12 Nested If/Else Instructions When an If/Else instruction is placed inside another If/Else instruction The inner If/Else executes only if the outer If/Else is true 4-13 Nested If/Else Instructions Start Penguin faces hole False “Too Far!” Within 2 meters False “Drats!” True Hole wider? True Penguin walks Penguin falls in End 4-14 Homework Read chapter 4 sections 4.1 – 4.3 Do labs in handout Due one week after assigned 4-15
© Copyright 2026 Paperzz