Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 31 Flow of Control Chapter 3. 2 Reminders Project 1 was due last night Project 2 released: due Sept 10:30 pm - No Late Submissions Follow.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Flow of Control Chapter 3.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 3 Edited by JJ Shepherd
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
Controlling Execution Dong Shao, Nanjing Unviersity.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
COMP Loop Statements Yi Hong May 21, 2015.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
Chapter 31 Flow of Control Chapter 3. 2 Objectives learn about Java branching statements learn about loops learn about the type boolean (optional) learn.
Chapter 31 Announcements Project 2 has been posted –Due Feb 1st at 10:00pm –Work ALONE! Help hours –Monday – Thursday, 7-10pm –LWSN B146 Quiz solutions.
Flow of Control Chapter 3. JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
COS 260 DAY 5 Tony Gauvin.
Chapter 3 Edited by JJ Shepherd
Flow of Control.
Chapter 3 Branching Statements
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
JavaScript: Control Statements.
Flow of Control Chapter 3 Chapter 3.
Loops A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is.
Flow of Control Chapter 3.
Flow of Control Chapter 3.
Chap 7. Advanced Control Statements in Java
Controlling Program Flow
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.
CSS 161: Fundamentals of Computing
Presentation transcript:

Flow of Control Chapter 3

Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean

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.

Branching Statements: Outline The if-else Statement Introduction to Boolean Expressions Nested Statements and Compound Statements Multibranch if-else Statements The switch Statament (optional) The Conditional Operator

The if-else Statement A branching statement that chooses between two possible actions. syntax if (Boolean_Expression) Statement_1 else Statement_2 example if (count < 3) total = 0 else total = total + count

Compound Statements To include multiple statements in a branch, enclose the statements in braces. if (count < 3) { total = 0; count = 0; } When a list of statements is enclosed in braces ( {} ), they form a single compound statement.

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;

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

Java Comparison Operators

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

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)

Negating a Boolean Expression A boolean expression can be negated using the “not” ( ! ) operator. syntax !(Boolean_Expression) example (a || b) && !(a && b) which is the exclusive or

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

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.

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”))

Testing Strings for Equality

Method compareTo syntax String_1.compareTo(String_2) Method compareTo returns –a negative number if String_1 precedes String_2 –zero if the two strings are equal –a positive number of String_2 precedes String_1.

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.

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);

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.

Nested Statements, cont. subtly different forms first formsecond formif (a > b) { if (c > d) if (c > d) e = f; e = f;else } g =h; else g = h; oops!

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

Multibranch if-else Statements, cont.

equivalent code

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 and called the controlling expression.

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 is searched for a case label matching the controlling expression.

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.

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.

The switch Statement, cont. syntax switch (Controlling_Expression) { case Case_Label: Statement(s); break; case Case_Label: … default: … }

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.

Java Loop Statements: Outline the while Statement the do-while Statement the for Statement

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.

the while Statement, cont.

syntax while (Boolean_Expression) Body_Statement or while (Boolean_Expression) { First_Statement Second_Statement … }

the while Statement, cont.

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!

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

The do-while Statement, cont.

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. A negative growth rate in the preceding problem causes totalBugVolume always to be less than houseVolume, so that the loop never ends.

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

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

The for Statement, cont.

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

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.

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).

The break Statement in Loops, cont.

The continue Statement in Loops A continue statement is used to skip remained statements and proceed next loop. Example for (int i=0; I < 5; ++i) { System.out.print(‘A’); continue; System.out.print(‘B’); } Prints AAAAA

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(“/ by 0”); System.exit(0); }

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.

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

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 = 12000) && (cabinPressure > 30) && …)

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)...

Truth Tables

Precedence Rules Parentheses should be used to indicate the order of operations. When parentheses are omitted, the order of operation is determined by precedence rules. Operations with higher precedence are performed before operations with lower precedence. Operations with equal precedence are done left-to- right (except for unary operations which are done right-to-left).

Precedence Rules, cont.

In what order are the operations performed? score 90 (score 90 (score 90)

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.

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 ||.

Summary You have learned about Java branching statements. You have learned about loops. You have learned about the type boolean.