Problem Solving with Decisions

Slides:



Advertisements
Similar presentations
CSI 1306 PROGRAMMING IN VISUAL BASIC PART 2. Part 2  1. Strings  2. Translating Conditional Branch Instructions  3. Translation Set 2  4. Debugging.
Advertisements

CS&E 1111 ExIFs IFs and Nested IFs in Excel Objectives: Using the If function in spreadsheets Nesting If functions.
5.04 Apply Decision Making Structures
Selection (decision) control structure Learning objective
Control Structures Corresponds with Chapters 3 and 4.
Lesson 5 - Decision Structure By: Dan Lunney
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
ITEC113 Algorithms and Programming Techniques
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
Basic Elements of Programming A VB program is built from statements, statements from expressions, expressions from operators and operands, and operands.
Pseudocode and Algorithms
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure.
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
ALGORITHMS AND FLOWCHARTS
Apply Sub Procedures/Methods and User Defined Functions
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
PROGRAMMING, ALGORITHMS AND FLOWCHARTS
Programming Logic and Design Fourth Edition, Introductory
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Computer Science Selection Structures.
Chapter 4: The Selection Process in Visual Basic.
Problem Solving with the Sequential Logic Structure Lesson 5 McManusCOP10061.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Lecture Set 5 Control Structures Part A - Decisions Structures.
1 CC111 Lec9 : Visual Basic Visual Basic (3) Lecture 9.
Problem Solving with Decisions
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
Flow of Control Part 1: Selection
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
Programming, an introduction to Pascal
1 Flow Control Ifs, loops. 2 Data Type At the lowest level, all data in a computer is written in 1’s and 0’s (binary) How the data gets interpreted, what.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
`. Lecture Overview Structure Programming Basic Control of Structure Programming Selection Logical Operations Iteration Flowchart.
4-1 Chapter 4 The Selection Process in VB.NET. 4-2 Learning Objectives Understand the importance of the selection process in programming. Describe the.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Lesson 5 McManus COP  Algorithm Instructions  Sequential Logic Structure  Solution Development McManusCOP10062.
COMPUTER PROGRAMMING I 5.04 Apply Decision Making Structures.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
110 F-1 Decisions and Conditions Chapter 4: We can design a form We can calculate To make our programs more powerful, we need to be able to make choices.
Controlling Program Flow with Decision Structures.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand how decisions are made in a computer ❏ To understand the logical.
Computer Science Up Down Controls, Decisions and Random Numbers.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Sub Procedures Chapter 6-Part 1. Chapter 6 Part 12 Event Procedures Code that occurs based upon event. Mouse click Got focus Repetitive code that might.
Visual Basic Fundamental Concepts
5.04 Apply Decision Making Structures
Chapter 5- Control Structures: Part 2
Visual Basic 6 (VB6) Data Types, And Operators
UNIT 4 Lesson 13 If statements.
Control Structures: Part 2
The Selection Structure
ALGORITHMS AND FLOWCHARTS
Visual Basic..
Structured Program
ALGORITHMS AND FLOWCHARTS
` Structured Programming & Flowchart
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Chapter 3: Selection Structures: Making Decisions
Presentation transcript:

Problem Solving with Decisions COP1006 4/25/2017 Problem Solving with Decisions Lesson 6 COP1006 McManus COP1006_06

Overview The Decision Logic Structure The If Instructions COP1006 4/25/2017 Overview The Decision Logic Structure The If Instructions Using Straight-through Logic Using Positive Logic Using Negative Logic Logic Conversion Which Decision Logic? Decision Tables COP1006 McManus COP1006_06

Flowchart Symbols Decision Process Assign Decision Process Assign True/False/Else Process Assign Decision Process Assign COP1006 McManus

Decisions, Decisions… Zzzzz! Oh, no! Alarm goes off! Snooze Snooze or Off? Snooze = 9? Snooze < 9 Sleep or Get up? Go Back to Sleep Get Dressed. . . COP1006 McManus

Decision Logic Structure Allows us to ask questions of our data. Similar to the way we think. We make decisions every day. Have two parts: recognition of what action to take (you have to get out of bed) and execution of that action (you actually jump up out of bed) COP1006 McManus

Common Forms The If Statement The Case Statement The Switch Statement The Single Selection If/Then The Double If/Then/Else The Multiple If/Then/Else The Case Statement The Switch Statement COP1006 McManus

Three Types of Decisions Straight-through Logic All decisions are processed sequentially, one after another. Least efficient, but most thorough Positive Logic Processing flow continues through the module instead of processing succeeding decisions, once the result is True. Negative Logic Flow is based on result being False. Nested decisions use Positive or Negative, but not Straight-through. COP1006 McManus

Straight-through F T F T All conditions are tested. Least efficient, but most exhaustive. F T F T COP1006 McManus

Positive Logic T F T F Uses If/Then/Else instructions Continues processing based on True results T Grade >= 90 F LtrG = “A” Grade >= 80 F T LtrG = “Other” LtrG = “B” Note that the strings are in quotations marks! COP1006 McManus

Negative Logic Executes process based on False Processes another decision when the result is True Grade < 90 T F Grade < 80 LtrG = “A” F T LtrG = “B” LtrG = “Other” COP1006 McManus

So, Which Do You Use? Optimum? Reality? The Goal Evaluate all three Reality? this almost never happens The Goal Easiest to understand Requires fewest tests Easiest to maintain Avoid the trap of always using the same COP1006 McManus

If Statements COP1006 McManus

The Single Selection IF Syntax If condition Then statement(s) End If Tests for one thing only. If the statement results in a False, it drops out without performing the statements. Very efficient, but not very flexible Grade >= 60 true false Display “Passed” COP1006 McManus

Example If Grade <= 100 and Grade >= 90 Then LetterGrade = “A” EndIf This asks the question: if the value stored in Grade is less than or equal to 100 and is greater than or equal to 90, then LetterGrade takes on the value of the character “A”. Condition COP1006 McManus

A Classic Example Private Sub Swap(X, Y) ‘X & Y passed in Dim Temp As Integer ‘local variable If X > Y Then Temp = X ‘Copies X into Temp X = Y ‘Copies Y into X Y = Temp ‘Copies Temp into Y End If End Sub VB code COP1006 McManus

The Double Selection If Allows two questions to be asked Syntax If condition Then statement(s) Else statement(s) End If Grade >= 60 true Display “Passed” false “Failed” COP1006 McManus

An Example If Grade >= 60 Then LetterGrade = “Passed” Else LetterGrade = “Failed” End If Notice that there are two exclusive options. Greater than or equal to 60 or Less than. No other option is available. COP1006 McManus

An Another Example If Hours > 40 Then Pay = PayRate * (40 + (1.5 * (Hours – 40))) Else Pay = PayRate * Hours End If Another way to write: Pay = (40 * PayRate) + _ ((1.5 * PayRate) * (Hours - 40)) COP1006 McManus

The Multiple Selection If The If/Then/Else permits multiple questions Always place the most likely to occur first. Increases efficiency COP1006 McManus

Example Notice Indentions Grade >= 90 true LetterGrade = “A” false If Grade >= 90 Then LetterGrade = “A” ElseIf Grade >= 80 Then LetterGrade = “B” ElseIf Grade >= 70 Then LetterGrade = “C” ElseIf Grade >= 60 Then LetterGrade = “D” Else LetterGrade = “F” End If Grade >= 80 true LetterGrade = “B” false Grade >= 70 true LetterGrade = “C” false Grade >= 60 true LetterGrade = “D” false LetterGrade = “F” Notice Indentions COP1006 McManus

Would you want me to use this one for your grades? How About This One? If Grade < 60 Then LetterGrade = “F” ElseIf Grade >= 60 Then LetterGrade = “D” ElseIf Grade >= 70 Then LetterGrade = “C” ElseIf Grade >= 80 Then LetterGrade = “B” Else LetterGrade = “A” End If Would you want me to use this one for your grades? COP1006 McManus

Nested Vs. Multiple if condition then if condition then Nested Ifs Multiple-Alternative Ifs if condition then if condition then if condition then statement1 if condition then else if condition then statement1 statement2 else else if condition then else statement3; else; {next statement} {next statement} nested ifs Which is easier to read? debug? COP1006 McManus

Forces each decision to be tested Nested If’s Forces each decision to be tested If Grade < 90 Then If Grade < 80 Then If Grade < 70 Then If Grade < 60 Then LetterGrade = “F” Else LetterGrade = “D” Else LetterGrade = “C” Else LetterGrade = “B” Else LetterGrade = “A” End If Ugly, isn’t it? COP1006 McManus

Logical Operators & Opposites Called Logical Opposites When switching between Positive and Negative Logic, change all < to >= <= to > > to <= >= to < = to <> <> to = And…exchange Then statements with Else statements COP1006 McManus

The Case & The Switch COP1006 McManus

The Case Statement Is similar to a series of If/Then/Else statements. Syntax: Select Case testvalue Case value1 statement group 1 Case value2 statement group 2 End Select COP1006 McManus

Case Flow Chart True Case a Case a action False True Case b Case b action False Case Else Case Else action COP1006 McManus

Case Example Select Case Grade Case 90..100 LetterGrade = “A” LetterGrade = “B” Case 70..79.9 LetterGrade = “C” Case 60..69.9 LetterGrade = “D” Else LetterGrade = “F” End Select COP1006 McManus

The Switch Statement Related to the If/Then/Else structure. Each argument that is passed to Switch is either a condition or a value. All possible values must be accounted for because there is no Else. COP1006 McManus

Switch Flow Chart Switch a True Switch a action False Switch b True Switch b action False Switch c Switch c action True COP1006 McManus

Switch Example LetterGrade = Switch _ (grade >= 90, “A”, _ grade >= 80, “B”, _ grade >= 70, “C”, _ grade >= 60, “D”, _ grade < 60, “F”) Much more concise than even the Case statement, but not in every language. COP1006 McManus

Decision Tables COP1006 McManus

Decision Tables Exist in several different forms Most consist of 4 parts: The conditions The actions The combinations of True and False for the conditions The action to be taken or the consequences for each combination of conditions. COP1006 McManus

Decision Table Example Filing Status (Condition) Single or Divorced Married filing Jointly or Qualifying Widower Married filing separately Head of Household Select tax rate (Action) a. Single b. Married jt c. Married sp d. Head hshd X Compute standard deduction (Action) a. $4,000 b. $2,500 c. $1,500 McManus COP1006

Another Decision Table Example How would you set up a Decision Table for Numeric Grades associated with Letter Grades? COP1006 McManus

Decision Table Solution Letter Grade (Solution)  Numeric Grade (Condition)  A B C D F 90 <= n X 80 <= n < 90 70 <= n < 80 60 <= n < 70 < 60 COP1006 McManus

Let’s work a problem… COP1006 McManus

The Problem Write the calculation module to choose the largest number from a set of three numbers, A, B, and C. COP1006 McManus

The Flow Chart False If A > B True False If B > C True False If A > C True Largest = C Largest = B Largest = C Largest = A COP1006 McManus

Pseudocode Solution If A is greater than B Then A is > B If A is greater than C Then A is > C Largest equals A A is > B & A > C Else Largest equals C A is < B & B < C If B is greater than C Then Largest equals B A is < B & B > C Largest equals C A is < B & C > B End If COP1006 McManus

Modify? How would you modify the logic to print the results in order, A, B, C? What are the possible outputs that you would expect to see? A, B, C B, C, A C, B, A A, C, B B, A, C C, A, B COP1006 McManus

Decision Table Solution Largest  A B C Order  A B C X A C B B C A B A C C B A C A B McManus COP1006

Coding the Problem In Visual Basic Note: Again, up this point it didn’t matter what language we use… COP1006 McManus

Yes, I know…the variables are not mnemonic! Data Dictionary Variable Name Data Type Module Defined Domain Scope A Short 2 bytes GetInput Calculate 0 < n < 10 Global B C Yes, I know…the variables are not mnemonic! McManus COP1006

VB Solution – Declare Variables Option Explicit On ' Input Values by User Dim A As Short Dim B As Short Dim C As Short COP1006 McManus

VB Solution - Get Input Private Sub txtNum1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtNum1.TextChanged 'converts user input to numeric format A = Val(txtNum1.Text) End Sub Private Sub txtNum2_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtNum2.TextChanged B = Val(txtNum2.Text) Private Sub txtNum3_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtNum3.TextChanged C = Val(txtNum3.Text) COP1006 McManus

VB Solution – Calculate Result Private Sub Calculate _ (ByVal A, ByVal B, ByVal C) Dim Largest As Short If A > B Then If A > C Then Largest = A Else Largest = C End If ElseIf B > C Then Largest = B Else Largest = C End If lblInstructions.Text = _ ("The Largest number is " & _ CStr(Largest)) End Sub COP1006 McManus

VB Solution - Produce Output Private Sub cmdPrintResult_Click() lblOutput.Text = ("A = " & CStr(A) & _ " B = " & CStr(B) & _ " C = " & CStr(C)) End Sub COP1006 McManus

VB Solution – the Form COP1006 McManus

Getting the Input 1st step 2nd step 3rd step COP1006 McManus

Calculating the Solution COP1006 McManus

Testing the Solution Input Variables to be tested A B C any numeric value greater than 0 and less than 10 B C COP1006 McManus

Summary - Reminder Analyze the Problem Being able to restate the problem is one indicator that you understand the problem Develop the Structure Chart (or flow chart of its subparts) Develop the Algorithms Develop the Data Dictionary Develop the Decision Table Develop the Code Test the Solution COP1006 McManus

Next? Problem Solving with Iteration COP1006 McManus