control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · •...

28
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying: Java Software Solutions by Lewis & Loftus Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne CSC 1051 M.A. Papalaskari, Villanova University Control flow, conditionals, boolean expressions, block statements, nested statements

Upload: others

Post on 07-Oct-2020

22 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

CSC 1051 – Algorithms and Data Structures I

Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying: •  Java Software Solutions by Lewis & Loftus •  Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne

CSC 1051 M.A. Papalaskari, Villanova University

Control flow, conditionals, boolean expressions, block statements, nested statements

Page 2: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

//************************************************************* // GPA.java Author: Joyce/Papalaskari // Demonstrates the use of Scanner input and simple computation. //************************************************************* import java.util.Scanner; public class GPA { public static void main (String[] args) //------------------------------------------------------------ // Inputs the quality points and credits and calculates GPA. //----------------------------------------------------------- { double qp, credits, gpa; Scanner scan = new Scanner(System.in); // get input System.out.print ("Enter Quality Points > "); qp = scan.nextInt(); System.out.print ("Enter Credits > "); credits = scan.nextInt(); // output values entered System.out.println ("\nQuality Points: " + qp); System.out.println ("Credits: " + credits); // calculate & output GPA gpa = qp / credits; System.out.println ("\n\tGPA: " + gpa); // print goodbye message System.out.println ("Thanks for using my program."); } }

variables: qp, credits, gpa Algorithm:

1. Input qp 2. Input credits 3. Output values entered 4. gpa = qp / credits 5. Print gpa 6. Print goodbye message

CSC 1051 M.A. Papalaskari, Villanova University

What if credits is 0 ??

Previous Example

Java Programè Algorithm è

Page 3: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Improved algorithm

CSC 1051 M.A. Papalaskari, Villanova University

variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. Output values entered if credits equals 0

•  Print “No gpa yet” else

•  gpa = qp / credits •  Print gpa

5. Print goodbye message

4.

Page 4: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

CSC 1051 M.A. Papalaskari, Villanova University

variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. Output values entered if credits equals 0

•  Print “No gpa yet” else

•  gpa = qp / credits •  Print gpa

5. Print goodbye message

4.

Java code

if (credits == 0) System.out.println ("No GPA yet"); else { gpa = qp / credits; System.out.println ("GPA: " + gpa); }

Page 5: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. Output values entered if credits equals 0

•  Print “No gpa yet” else

•  gpa = qp / credits •  Print gpa

5. Print goodbye message

//************************************************************* // GPA_updated.java Author: Joyce/Papalaskari // // Demonstrates the use of conditional statements. //************************************************************* import java.util.Scanner; public class GPA_Updated { public static void main (String[] args) //---------------------------------------------------------- // Reads the quality points and credits and calculates GPA. //---------------------------------------------------------- { double qp, credits, gpa; Scanner scan = new Scanner(System.in); // get input System.out.print ("Enter Quality Points > "); qp = scan.nextInt(); System.out.print ("Enter Credits > "); credits = scan.nextInt(); // output values entered System.out.println ("\nQuality Points: " + qp); System.out.println ("Credits: " + credits); // calculate and output GPA, if possible if (credits == 0) System.out.println ("No GPA yet"); else { gpa = qp / credits; System.out.println ("GPA: " + gpa); } // Print goodbye message System.out.println ("Thanks for using my program."); } }

CSC 1051 M.A. Papalaskari, Villanova University

4.

Updated program

Page 6: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Control flow •  Sequence of statements that are

actually executed in a program

CSC 1051 M.A. Papalaskari, Villanova University

statement 1

statement 2

statement 3

statement 4

Page 7: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Control flow •  Sequence of statements that are

actually executed in a program

CSC 1051 M.A. Papalaskari, Villanova University

statement 1

statement 2

statement 3

statement 4

condition 1

condition 2

statement 2

statement 4 true

true

false

false

statement 3 This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php

statement 1

Conditional and Repetition statements: enable us to alter control flow

Page 8: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Control flow

CSC 1051 M.A. Papalaskari, Villanova University

. .

statement 2

statement 3

statement 4

. .

. .

. .

input qp

input credits

gpa = qp / credits

print gpa

statement 4 . . print goodbye message

•  Sequence of statements that are actually executed in a program

•  Example:

Page 9: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Control flow

CSC 1051 M.A. Papalaskari, Villanova University

. .

statement 2

statement 3

statement 4

true

false

Example

. .

. .

. .

input qp

input credits

gpa = qp / credits

print gpa

. .

statement 2 . .

input qp

input credits

credits is zero?

statement 3

statement 4

. .

. .

gpa = qp / credits

print gpa

statement 4 . . print goodbye message

. . print “no GPA yet”

statement 4 . . print goodbye message

•  Sequence of statements that are actually executed in a program

•  Example:

Page 10: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Java Conditional statements alter the linear flow of control. They use boolean expressions to determine what to do next. Example: if (credits == 0)

System.out.println ("No GPA yet");

else { gpa = qp / credits; System.out.println ("GPA: " + gpa); }

CSC 1051 M.A. Papalaskari, Villanova University

A boolean expression

if true, do this

if more than one statement, enclose in braces

if false, do these

Page 11: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Java relational operators

•  relational operators can be used with numeric types and produce boolean results:

== equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to

•  Note the difference between the equality operator (==) and the assignment operator (=)

CSC 1051 M.A. Papalaskari, Villanova University

Page 12: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Conditional statements

condition evaluated

statement 1

true

false

statement2

CSC 1051 M.A. Papalaskari, Villanova University

condition evaluated

statement

true

false

if ( condition ) statement1; else statement2;

if ( condition ) statement; // no else clause

Page 13: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Example:

CSC 1051 M.A. Papalaskari, Villanova University

How do we fix output to use singular/plural as appropriate? For example: Enter the total amount to be given as change: 18

That amount can be given as: 0 quarters 1 dimes 1 nickels 3 pennies

get rid of this!

Page 14: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Example:

CSC 1051 M.A. Papalaskari, Villanova University

Create an application called Vacation that prompts for and inputs an integer representing someone’s age and then suggests an appropriate vacation destination. One of two destinations should be suggested depending on whether person is over 30.

age > 30?

print “Florida”

true

false

print “Grand Canyon”

input age

print “goodbye”

How old is the traveler ?: 15 Suggestion: Grand Canyon.

sample output

Page 15: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Nested conditionals

CSC 1051 M.A. Papalaskari, Villanova University

condition 1

condition 2

statement 2

statement 4 true

true

false

false

statement 3

This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php

statement 1

statement 1;

if (condition 1)

statement 2;

else

if (condition 2)

statement 4;

else

statement 3;

statement 5;

statement 5

Page 16: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Another example:

CSC 1051 M.A. Papalaskari, Villanova University

Create an application called Vacation that prompts for and inputs an integer representing someone’s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50.

How old is the traveler ?: 59 Suggestion: Florida.

sample output

Page 17: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Java Logical Operators

•  logical operators can be used with boolean operands to express more complex boolean conditions:

! Logical NOT && Logical AND || Logical OR

CSC 1051 M.A. Papalaskari, Villanova University

Page 18: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

CSC 1051 M.A. Papalaskari, Villanova University

Create an application called Vacation that prompts for and inputs an integer representing someone’s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50.

How old is the traveler ?: 59 Suggestion: Florida.

sample output

Vacation example revisited:

Page 19: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Boolean Expressions •  The reserved words true and false are the only valid

values for a boolean type

•  Example: boolean variables:

CSC 1051 M.A. Papalaskari, Villanova University

boolean aboveAgeLimit = false;

boolean usePlural = hours > 1; boolean expression using a relational operator

Page 20: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Logical Operators – Another Example if (total < MAX + 5 && (!found)) System.out.println ("Processing…");

CSC 1051 M.A. Papalaskari, Villanova University

•  All logical operators have lower precedence than the relational operators

•  The ! operator has higher precedence than && and ||

total 103

MAX 100

found false

Page 21: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Logical NOT •  The logical NOT operation is also called logical

negation or logical complement

•  If some boolean condition a is true, then !a is false; if a is false, then !a is true

•  Logical expressions can be shown using a truth table:

CSC 1051 M.A. Papalaskari, Villanova University

a !a

true falsefalse true

Page 22: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Logical AND and Logical OR •  The logical AND expression a && b

is true if both a and b are true, and false otherwise

•  The logical OR expression a || b

is true if a or b or both are true, and false otherwise

CSC 1051 M.A. Papalaskari, Villanova University

a b a && b a || b

true true true truetrue false false truefalse true false truefalse false false false

Page 23: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Quick Check 1

CSC 1051 M.A. Papalaskari, Villanova University

What does this statement do? if (found || !done) System.out.println("Ok");

found false

done false

Page 24: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Quick Check 2

CSC 1051 M.A. Papalaskari, Villanova University

if (total != stock + warehouse) inventoryError = true;

total 20

stock 7

warehouse 12

inventoryError false

What does this statement do?

Page 25: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Boolean Expressions •  using truth tables – let’s try this one:

CSC 1051 M.A. Papalaskari, Villanova University

found done !done found || !done

false falsefalse truetrue falsetrue true

Page 26: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Boolean Expressions

CSC 1051 M.A. Papalaskari, Villanova University

total > MAX found !found total > MAX && !found

false falsefalse truetrue falsetrue true

•  using truth tables – another example:

Page 27: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

How much of a boolean expression do we need to evaluate before determining its value? *** Short-Circuited Operators •  The processing of && and || is “short-circuited” in

cases where the left operand is sufficient to determine the result (the right operand is not evaluated at all)

•  This can be both useful and dangerous!

if (count != 0 && total/count > MAX) System.out.println ("Testing.");

CSC 1051 M.A. Papalaskari, Villanova University

Page 28: Control flow, conditionals, boolean expressions, block ...map/1051/s17/03conditionals.pdf · • Java Software Solutions by Lewis & Loftus • Introduction to Programming in Java:

Indentation Revisited

•  Remember that indentation is for the human reader, and is ignored by the computer

if (total > MAX) System.out.println ("Error!!"); errorCount = errorcount + 1;;

Despite what is implied by the indentation, the increment will occur whether the condition is true or not

CSC 1051 M.A. Papalaskari, Villanova University