Flow of Control. Chapter 3. Chapter 3 1

Similar documents
Flow of Control. Chapter 3

Flow of Control. Chapter 3

Flow of Control. Chapter 3

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

4. Flow of Control: Loops. Objectives. Java Loop Statements: Outline 10/3/11. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

4. Flow of Control: Loops

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

Flow of Control: Loops

Flow of Control: Loops

Flow of Control: Loops. Chapter 4

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Flow of Control. Chapter

CONDITIONAL EXECUTION: PART 2

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Logic & program control part 2: Simple selection structures

Conditionals and Loops

CS1004: Intro to CS in Java, Spring 2005

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Topics. Chapter 5. Equality Operators

Flow Control. CSC215 Lecture

STUDENT LESSON A12 Iterations

Programming with Java

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

1007 Imperative Programming Part II

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 4: Conditionals and Loops

COMP Introduction to Programming If-Else Statement, Switch Statement and Loops

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Full file at

Flow of Control. 3.1 Branching Mechanism Boolean Expressions Loops Debugging 144

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Flow of Control. Chapter 3 Part 3 The Switch Statement

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Repetition, Looping. While Loop

Oct Decision Structures cont d

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Course Outline. Introduction to java

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Program Elements -- Introduction

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

What methods does the String class provide for ignoring case sensitive situations?

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Introduction to Control Statements

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

APCS Semester #1 Final Exam Practice Problems

Defining Classes and Methods

Pace University. Fundamental Concepts of CS121 1

Chapter 4: Conditionals and Loops

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Using Java Classes Fall 2018 Margaret Reid-Miller

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Chapter 3 Selection Statements

Chapter 3. Selections

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction. C provides two styles of flow control:

Chapter 4: Control Structures I (Selection)

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

2.8. Decision Making: Equality and Relational Operators

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

COMP 110 Introduction to Programming. What did we discuss?

Problem Solving With Loops

Programming with Java

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Full file at

Wed. Sep 27th 7-8PM EE170

Program Control Flow

Program Control Flow

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Full file at

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

AP Computer Science A

CS313D: ADVANCED PROGRAMMING LANGUAGE

2.5 Another Application: Adding Integers

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Java Flow of Control

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

Transcription:

Flow of Control Chapter 3 Chapter 3 1

Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement chooses between two or more possible actions. A loop statement repeats an action until a stopping condition occurs. Chapter 3 4

The if-else Statement A branching statement that chooses between two possible actions. syntax if (Boolean_Expression) Statement_1; else Statement_2; Chapter 3 6

The if-else Statement, example if (count < 3) cont. total = 0; else total = total + count; Chapter 3 7

The if-else Statement, class BankBalance cont. Chapter 3 8

Compound Statements To include multiple statements in a branch, enclose the statements in braces. if (count < 3) { } total = 0; count = 0; Chapter 3 9

Omitting the else Part If the else part is omitted and the expression after the if is false, no action occurs. syntax if (Boolean_Expression) Statement example if (weight > ideal) caloriesperday -= 500; Chapter 3 10

Introduction to Boolean Expressions The value of a boolean expression is either true or false. examples time < limit balance <= 0 Chapter 3 11

Java Comparison Operators Chapter 3 12

Compound Boolean Expressions Boolean expressions can be combined using the and (&&) operator. example if ((score > 0) && (score <= 100))... not allowed if (0 < score <= 100)... Chapter 3 13

Compound Boolean Expressions, cont. syntax (Sub_Expression_1) && (Sub_Expression_2) Parentheses often are used to enhance readability. The larger expression is true only when both of the smaller expressions are true. Chapter 3 14

Compound Boolean Expressions, cont. Boolean expressions can be combined using the or ( ) operator. example if ((quantity > 5) (cost < 10))... syntax (Sub_Expression_1) (Sub_Expression_2) Chapter 3 15

Compound Boolean Expressions, cont. The larger expression is true when either of the smaller expressions is true when both of the smaller expressions are true. The Java version of or is the inclusive or which allows either or both to be true. The exclusive or allows one or the other, but not both to be true. Chapter 3 16

Using == == is appropriate for determining if two integers or characters have the same value. if (a == 3) where a is an integer type == is not appropriate for determining if two floating points values are equal. Use < and some appropriate tolerance instead. if (abs(b - c) < epsilon) where b, c, and epsilon are floating point types Chapter 3 19

Using ==, cont. == is not appropriate for determining if two objects have the same value. if (s1 == s2), where s1 and s2 refer to strings, determines only if s1 and s2 refer the a common memory location. If s1 and s2 refer to strings with identical sequences of characters, but stored in different memory locations, (s1 == s2) is false. Chapter 3 20

Using ==, cont. To test the equality of objects of class String, use method equals. s1.equals(s2) or s2.equals(s1) To test for equality ignoring case, use method equalsignorecase. ( Hello.equalsIgnoreCase( hello )) Chapter 3 21

equals and equalsignorecase syntax String.equals(Other_String) String.equalsIgnoreCase(Other_String) Chapter 3 22

Testing Strings for Equality class StringEqualityDemo Chapter 3 23

Lexicographic Order Lexicographic order is similar to alphabetical order, but is it based on the order of the characters in the ASCII (and Unicode) character set. All the digits come before all the letters. All the uppercase letters come before all the lower case letters. Chapter 3 24

Lexicographic Order, cont. Strings consisting of alphabetical characters can be compared using method compareto and method touppercase or method tolowercase. String s1 = Hello ; String lowers1 = s1.tolowercase(); String s2 = hello ; if (s1.compareto(s2)) == 0 System.out.println( Equal! ); Chapter 3 25

Nested Statements An if-else statement can contain any sort of statement within it. In particular, it can contain another if-else statement. An if-else may be nested within the if part. An if-else may be nested within the else part. An if-else may be nested within both parts. Chapter 3 27

Nested Statements, cont. syntax if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1; else Statement_2; else if (Boolean_Expression_3) Statement_3; else Statement_4; Chapter 3 28

Nested Statements, cont. Each else is paired with the nearest unmatched if. If used properly, indentation communicates which if goes with which else. Braces can be used like parentheses to group statements. Chapter 3 29

Compound Statements When a list of statements is enclosed in braces ({}), they form a single compound statement. syntax { } Statement_1; Statement_2; Chapter 3 31

Compound Statements, cont. A compound statement can be used wherever a statement can be used. example if (total > 10) { } sum = sum + total; total = 0; Chapter 3 32

Multibranch if-else Statements syntax if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_2) Statement_2 else if (Boolean_Expression_3) Statement_3 else if else Default_Statement Chapter 3 33

class Grader Multibranch if-else Statements, cont. Chapter 3 34

Multibranch if-else equivalent code Statements, cont. Chapter 3 35

The switch Statement The switch statement is a mutltiway branch that makes a decision based on an integral (integer or character) expression. The switch statement begins with the keyword switch followed by an integral expression in parentheses called the controlling expression. Chapter 3 36

The switch Statement, cont. A list of cases follows, enclosed in braces. Each case consists of the keyword case followed by a constant called the case label a colon a list of statements. The list of cases is searched in order for a case label matching the controlling expression. Chapter 3 37

The switch Statement, cont. The action associated with a matching case label is executed. If no match is found, the case labeled default is executed. The default case is optional, but recommended, even if it simply prints a message. Repeated case labels are not allowed. Chapter 3 38

The switch Statement, cont. class MultipleBirths Chapter 3 39

The switch Statement, cont. The action for each case typically ends with the word break. The optional break statement prevents the consideration of other cases. The controlling expression can be anything that evaluates to an integral type. Chapter 3 40

The Conditional Operator if (n1 > n2) max = n1; else max = n2; can be written as max = (n1 > n2)? n1 : n2; The? and : together are call the conditional operator or ternary operator. Chapter 3 42

The Conditional Operator, cont. The conditional operator is useful with print and println statements. System.out.print( You worked + ((hours > 1)? hours ; hour )); Chapter 3 43

the while Statement also called a while loop A while statement repeats until a controlling boolean expression becomes false. If the controlling boolean expression is false initially, the while loop is not executed. The loop body typically contains a statement that ultimately causes the controlling boolean expression to become false. Chapter 3 46

the while Statement, cont. class WhileDemo Chapter 3 47

the while Statement, cont. syntax while (Boolean_Expression) Body_Statement; or while (Boolean_Expression) { First_Statement; Second_Statement; } Chapter 3 48

The do-while Statement also called a do-while loop similar to a while statement, except that the loop body is executed at least once syntax do Body_Statement while (Boolean_Expression); don t forget the semicolon at the end of the while line! Chapter 3 50

The do-while Statement, cont. class DoWhileDemo Chapter 3 51

The do-while Statement, cont. First, the loop body is executed. Then the boolean expression is checked. As long as it is true, the loop is executed again. If it is false, the loop is exited. equivalent while statement Statement(s)_S1 while (Boolean_Condition) Statement(s)_S1 Chapter 3 52

Infinite Loops A loop which repeats without ever ending is called an infinite loop. If the controlling boolean expression never becomes false, a while loop or a do-while loop will repeat without ending. Chapter 3 56

The for Statement A for statement executes the body of a loop a fixed number of times. example for (count = 1; count < 5; count++) System.out.println(count); System.out.println( Done ); Chapter 3 57

The for Statement, cont. syntax for (Initialization, Condition, Update) Body_Statement Body_Statement can be either a simple statement or a compound statement in {}. corresponding while statement Initialization while (Condition) Body_Statement_Including_Update Chapter 3 58

Multiple Initialization, etc. example for (n = 1, p = 1; n < 10; n++) p = p * n; Only one boolean expression is allowed, but it can consist of &&s, s, and!s. Multiple update actions are allowed, too. for (n = 1, p = 1; n < 10; n++, p * n) rarely used Chapter 3 61

The Empty for Statement What is printed by int product = 1, number; for (number = 1; number <= 10; number++); product = product * number; System.out.println(product);? The last semicolon in for (number = 1; number <= 10; number++); produces an empty for statement. Chapter 3 62

The Empty while Statement int product = 1, number = 1; while (number <= 10); { product = product * number; number++ } System.out.println(product); The last semicolon in while (number <= 10); produces an empty while loop body. Chapter 3 63

Choosing a Loop Statement If you know how many times the loop will be iterated, use a for loop. If you don t know how many times the loop will be iterated, but it could be zero, use a while loop it will be at least once, use a do-while loop. Generally, a while loop is a safe choice. Chapter 3 64

The break Statement in Loops A break statement can be used to end a loop immediately. The break statement ends only the innermost loop or switch statement that contains the break statement. break statements make loops more difficult to understand. Use break statements sparingly (if ever). Chapter 3 65

The break Statement in class BreakDemo Loops, cont. Chapter 3 66

The exit Method Sometimes a situation arises that makes continuing the program pointless. A program can be terminated normally by System.exit(0). example if (numberofwinners == 0) { } System.out.println( cannot divide by 0 ); System.exit(0); Chapter 3 67

Ending a Loop, cont. For large input lists, a sentinel value can be used to signal the end of the list. The sentinel value must be different from all the other possible inputs. A negative number following a long list of nonnegative exam scores could be suitable. 90 0 10-1 Chapter 3 72

Ending a Loop, cont. example - reading a list of scores followed by a sentinel value int next = keyboard.nextint(); while (next >= 0) { Process_The_Score next = keyboard.nextint(); } Chapter 3 73

Ending a Loop, cont. class ExamAverager Chapter 3 74

Nested Loops The body of a loop can contain any kind of statements, including another loop. In the previous example the average score was computed using a while loop. This while loop was placed inside a do-while loop so the process could be repeated for other sets of exam scores. Chapter 3 75

Loop Bugs common loop bugs unintended infinite loops off-by-one errors testing equality of floating-point numbers subtle infinite loops The loop may terminate for some input values, but not for others. For example, you can t get out of debt when the monthly penalty exceeds the monthly payment. Chapter 3 77

The Type boolean Boolean Expressions and Variables Truth Tables and Precedence Rules Input and Output of Boolean Values Chapter 3 83

The Type boolean, cont. The type boolean is a primitive type with only two values: true and false. Boolean variables can make programs more readable. if (systemsareok) instead of if((temperature <= 100) && (thrust >= 12000) && (cabinpressure > 30) && ) Chapter 3 84

Boolean Expressions and Variables Variables, constants, and expressions of type boolean all evaluate to either true or false. A boolean variable can be given the value of a boolean expression by using an assignment operator. boolean ispositive = (number > 0);... if (ispositive)... Chapter 3 85

Naming Boolean Variables Choose names such as ispositive or systemsareok. Avoid names such as numbersign or systemstatus. Chapter 3 86

Short-circuit Evaluation Sometimes only part of a boolean expression needs to be evaluated to determine the value of the entire expression. If the first operand associated with an is true, the expression is true. If the first operand associated with an && is false, the expression is false. This is called short-circuit or lazy evaluation. Chapter 3 92

Short-circuit Evaluation, cont. Short-circuit evaluation is not only efficient, sometimes it is essential! A run-time error can result, for example, from an attempt to divide by zero. if ((number!= 0) && (sum/number > 5)) Complete evaluation can be achieved by substituting & for && or for. Chapter 3 93

Input and Output of Boolean example boolean boo = false; Values System.out.println(boo); System.out.print( Enter a boolean value: ); Scanner keyboard = new Scanner (System.in); boo = keyboard.nextboolean(); System.out.println(boo); Chapter 3 94

Input and Output of Boolean Values, cont. dialog false Enter a boolean value: true true Chapter 3 95

Using a Boolean Variable to End a Loop example boolean numberslefttoread = true while (numberslefttoread) { next = keyboard.nextint() if (next < 0) numberslefttoread = false; else Process_Next_Number } Chapter 3 96

(optional) Graphics Supplement: Outline Specifying a Drawing Color The drawstring Method A JOptionPane Yes/No Window Chapter 3 98

Specifying a Drawing Color When drawing a shape inside an applet s paint method, think of the drawing being done with a pen that can change colors. The method setcolor changes the color of the pen. canvas.setcolor(color.yellow); Drawings done later appear on top of drawings done earlier. Chapter 3 99

Specifying a Drawing Color, cont. Chapter 3 100

Specifying a Drawing Color, cont. Chapter 3 101

The drawstring Method similar to other drawing methods, but used to draw text canvas.drawstring( Hello,10,20); syntax Graphics_Object.drawString(String, X, Y); Chapter 3 105

A JOptionPane Yes/No Window used to present the user with a yes/no question The window contains the question text two buttons labeled Yes and No. Chapter 3 106

A JOptionPane Yes/No Window, cont. example int answer = JOptionPane.showConfirmDialog(null, End program?, Want to end?, JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) System.exit(0); else System.out.println( once more ); Chapter 3 107

A JOptionPane Yes/No Window, cont. Chapter 3 108

A JOptionPane Yes/No Window, cont. JOptionPane.showConfirmDialog returns an int value named either YES_OPTION or NO_OPTION, but you do not need to think of them as ints. The second argument ( End program? in our example) appears in the window. The third argument ( Want to end? in our example) is displayed as the title of the window. Chapter 3 109

A JOptionPane Yes/No Window, cont. The last argument (JOptionPane.YES_NO_OPTION in our example). requests a window with yes and no buttons. The first argument (null in our example) affects the placement of the window on the screen. Simply use null for now. Chapter 3 110