Logic & program control part 3: Compound selection structures.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 5 Selection Statements Animated Version.
Chapter 4 - Control Statements
Fundamental of C programming
Question from the last class What happens if we cast “too large” float/double to an int? int has range float a=1e10f; int b=(int)
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Chapter 4 Making Decisions
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
If statements Chapter 3. Selection Want to be able to do a statement sometimes, but not others if it is raining, wear a raincoat. Start first with how.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Control Structures I (Selection)
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 - Algorithms and Design
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Copyright 2003 Scott/Jones Publishing Making Decisions.
BACS 287 Programming Logic 2. BACS 287 Sequence Construct The sequence construct is the default execution mode for the CPU. The instructions are executed.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Chapter Making Decisions 4. Relational Operators 4.1.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
C++ Programming Control Structures I (Selection).
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 5 Topics Data Type bool
Chapter 4: Control Structures I
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Control Structures I
Sequence, Selection, Iteration The IF Statement
Chapter 4: Making Decisions.
2.5 Another Java Application: Adding Integers
Chapter 4: Making Decisions.
SELECTION STATEMENTS (1)
Control Statement Examples
Chapter 4: Control Structures I
Topics Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements Nested.
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Control Statements.
Presentation transcript:

Logic & program control part 3: Compound selection structures

Multi-way selection Many algorithms involve several possible pathways to a solution A simple if/else structure provides two alternate paths; if more than two paths are possible, a multi-way branching structure, such as a nested if/else or switch statement

Nested if/else structures An if/else structure can contain another if/else structure When this happens, the structures are said to be nested This occurs when one condition test depends on the result of another such test

Nested if/else syntax if (expression 1) { statement(s); // perform these if expression 1 is true } else if (expression 2) { statement(s); // perform these if expression 1 is false, expression 2 is true } … else if (expression n) { statement(s); // perform if nth expression true, all previous false } else { statements(s); // perform if all expressions false }

Nested if/else Statements Each expression is evaluated in sequence, until some expression is found that is true. Only the specific statement following that particular true expression is executed. If no expression is true, the statement following the final else is executed. Actually, the final else and final statement are optional. If omitted, and no expression is true, then no statement is executed.

Example Suppose you are assigned the task of writing a simple math quiz program: –The user selects from a menu of options describing different types of problems –When an option has been chosen, the program displays a problem (using randomly-generated numbers) and prompts the user for an answer –The program displays a message informing the user if s/he was right or wrong, and provides the correct answer if the user didn’t A fragment of this program appears on the next 2 slides

Simple calculator – menu processing section // ************ display problem & generate correct answer ************* if (choice == 1) { System.out.println(op1 + “ + “ + op2 + “ = “ ); answer = op1 + op2; } else if (choice == 2) { System.out.println(op1 + “ - “ + op2 + “ = “ ); answer = op1 - op2; } else if (choice == 3) { System.out.println(op1 + “ * “ + op2 + “ = “ ); answer = op1 * op2; }

Program fragment continued else if (choice == '4') { System.out.println(op1 + “ / “ + op2 + “ = “ ); answer = op1 / op2; } else // user chose something that wasn't on the menu { System.out.println ("That was not a valid option. You must be punished.“); }

Example Check the number of credit hours earned by a student, and print his/her class status as a freshman, sophomore, junior, or senior, as follows: –if more than 90 credit hours earned, print senior –if between 60 and 89 credit hours, print junior –if between 30 and 59 credit hours, print sophomore –otherwise, print freshman

Java code if ( creditsEarned >= 90 ) System.out.print( “SENIOR STATUS\n ”) ; else if (creditsEarned = 60 ) System.out.print ( “JUNIOR STATUS\n ”) ; else if ( creditsEarned >= 30 && creditsEarned <= 59) System.out.print“SOPHOMORE STATUS\n ”) ; else if (creditsEarned < 30) System.out.print ( “FRESHMAN STATUS\n ”) ;

Equivalent logic The logic in a selection structure can often be written in several different ways For example, on the previous slide we had logic that printed a student’s class status based on credit hours earned The next slide illustrates the same logic, but written more efficiently In general, strive for the simplest expressions, with the least amount of evaluation required This not only makes code more efficient, but also easier to test and debug

Java code if ( creditsEarned >= 90 ) System.out.print ( “SENIOR STATUS\n ”) ; else if ( creditsEarned >= 60 ) System.out.print ( “JUNIOR STATUS\n ”) ; else if ( creditsEarned >= 30 ) System.out.print ( “SOPHOMORE STATUS\n ”) ; else System.out.print ( “FRESHMAN STATUS\n ”) ;

More examples – write nested if/else structures for each Display one word to describe the int value of number as “Positive”, “Negative”, or “Zero” Your city classifies a pollution index –less than 35 as “Pleasant”, –35 through 60 as “Unpleasant”, – above 60 as “Health Hazard.”

Notes on nested if/else structures The number of “ifs” and “elses” need not be equal, but each else must be preceded by an if By default, an else clause is associated with the closest preceding if that doesn’t already have an else

Example - what is the output? float average; average = 100.0; if ( average >= 60.0 ) if ( average < 70.0 ) System.out.print (“Marginal PASS\n”); else System.out.print(“FAIL\n”);

Write a program to control your life using selection structures: Every Monday thru Friday you go to class. When it is raining you take an umbrella. But on the weekend, what you do depends on the weather. If it is raining you read in bed. Otherwise, you have fun outdoors.

// One variation import javax.swing.*; public class HowToLive { public static void main (String [] args) { int day; boolean raining; String input; input = JOptionPane.showInputDialog (null, “Enter day (use 1 for Sunday)”); day = Integer.parseInt(input); input = JOptionPane.showInputDialog (null, “If it’s raining, enter T; otherwise, enter F”); if (input == “T”) raining=true; else raining=false;

if ( ( day == 1) || (day == 7) ) // Sat or Sun { if (raining ) JOptionPane.showMessageDialog(null, “Read in bed”); else JOptionPane.showMessageDialog(null, “Have fun outdoors”); } else { JOptionPane.showMessageDialog(null, “Go to class ”); if (raining) JOptionPane.showMessageDialog (null, “Take an umbrella”); }

Another variation import javax.swing.*; public class HowToLive2 { public static void main (String [] args) { int day; boolean raining=false; String input; input = JOptionPane.showInputDialog(null, “Is it raining? (1=yes, 0=no): ”); if(input.equals(“1”)) raining=true; input= JOptionPane.showInputDialog(null, “What day is it? ”);

Another variation continued if (raining) { if (input.equals(“Sunday”) || input.equals(“Saturday”)) JOptionPane.showMessageDialog(null, “Read in bed” ); else JOptionPane.showMessageDialog(null, “Take an umbrella to class”); } // ends outer if else { if(!(input.equals( “Sunday”)) && (!(input.equals(“Saturday”))) JOptionPane.showMessageDialog(null, “Go to class”); else JOptionPane.showMessageDialog(null, “Go outside & play”); } // ends outer else } // ends main } // ends class HowToLive2

Logical equivalence We can see that nested if statements can be equivalent to anded expressions: if ((a > b) && (b > c)) could be written as: if (a > b) { if (b > c) … In the next example, we’ll use logical or to determine if a value lies outside a given range

Example using if/else if if (value < 1) System.out.println(“Value out of range”); else if (value > 100) System.out.println(“Value out of range”);

Example using logical or if ((value 100)) System.out.println(“Value out of range”);

Same example using && and ! if (!((value >= 0) && (value <=100))) System.out.println(“Value out of range”);

An alternative: the switch/case structure For problems like the calculator menu and how to spend your day examples, an alternative kind of selection control structure is available In a switch/case structure, the variable to be tested must be testable to discrete values; in other words, tested for equality

Switch/case syntax switch(expression) { case value1: statement(s); break; case value2: statement(s); break; … case valueN: statement(s); break; default: statement(s); } Notes: “expression” is usually, but doesn’t have to be, a single variable Each case label contains a possible value for the expression The values must be integral values; e.g. ints, longs, etc. - may be literal values or named constants

Simple calculator – if/else vs. switch if (choice == 1) { answer = op1 + op2; } else if (choice == 2) { answer = op1 - op2; } … else { System.out.println("not a valid option“); } switch (choice) { case 1: answer = op1 + op2; break; case 2: answer = op1 - op2; break; … default: System.out.println ("not a valid option“); }

How switch works The expression is evaluated; if a matching value is found next to one of the case labels, all statements following that case are executed until either: –a break statement is encountered or –the end bracket of the switch/case structure is encountered If no matching case is found, the statements following the default label are performed

The importance of the break statement The break statement at the end of each case terminates the switch statement at that point Case labels are just labels; once any valid case is found, all statements from then on will execute sequentially in the absence of a break – subsequent labels are ignored With break statements, only the statement(s) associated with the valid case will be performed

Syntax notes on switch structure Begin/end brackets surround the whole structure from the end of the switch() clause until the end of the last case No brackets surround the statements within individual cases; brackets would only be used there if a case contained another control structure which required its own set of brackets Default case is optional; works like final else in if/else structure

Switch with no brakes (breaks) int light; // 1 means red, 2 means green, 3 means yellow... switch (light) { case 1: System.out.println(“STOP!”); case 2: System.out.println(“GO!”); case 3: System.out.println(“Go real fast!”); } What happens when light is red?

Testing Selection Control Structures To test a program with branches, use enough data sets so that every branch is executed at least once This is called minimum complete coverage

How to Test a Program Design and implement a test plan A test plan is a document that specifies the test cases to try, the reason for each, and the expected output Implement the test plan by verifying that the program outputs the predicted results