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

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

Handout 4 Conditionals. Boolean Expressions.

Flow of Control. Chapter 3. Chapter 3 1

Flow of Control. Chapter 3

Flow of Control. Chapter 3

Flow of Control. Chapter 3

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

STUDENT LESSON A12 Iterations

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

Flow of Control. Chapter

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

Conditionals and Loops

Chapter 3: Program Statements

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Logical Operators and switch

Chapter 2. C++ Basics

Loops (while and for)

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

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.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

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

Chapter 4: Making Decisions

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

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Chapter 4: Making Decisions

The Java language has a wide variety of modifiers, including the following:

Topics. Chapter 5. Equality Operators

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 3. More Flow of Control

LECTURE 04 MAKING DECISIONS

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

CONDITIONAL EXECUTION: PART 2

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Full file at

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

COMP Primitive and Class Types. Yi Hong May 14, 2015

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

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

Information Science 1

Introduction to Java & Fundamental Data Types

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

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

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

Looping. Arizona State University 1

REPETITION CONTROL STRUCTURE LOGO

Information Science 1

Chapter 4: Control structures. Repetition

ARG! Language Reference Manual

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 3. Selections

CT 229 Java Syntax Continued

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

Flow of Control: Loops

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Chapter 4: Control structures

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Chapter 4 - Notes Control Structures I (Selection)

Logic & program control part 2: Simple selection structures

Chapter Goals. Contents LOOPS

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

Chapter 3 Selection Statements

Iteration statements - Loops

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Score score < score < score < 65 Score < 50

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Accelerating Information Technology Innovation

Lecture 5 Tao Wang 1

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

CS1004: Intro to CS in Java, Spring 2005

Darrell Bethea May 25, 2011

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Programming Constructs -- Introduction

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

Lecture 7 Tao Wang 1

5. Control Statements

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Flow Control. CSC215 Lecture

Full file at

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

Simple Java Programming Constructs 4

Control Structures in Java if-else and switch

Introduction. C provides two styles of flow control:

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

Programming with Java

Chapter 4: Conditionals and Loops

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Programming Logic and Design Sixth Edition

Transcription:

Flow of Control Branching Loops exit(n) method Boolean data type and expressions Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

Flow of Control is the execution order of instructions in a program All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Branching or Selection - a choice of at least two either go to the next instruction or jump to some other instruction 3. Loop or Repetition - a loop (repeat a block of code) at the end of the loop either go back and repeat the block of code or continue with the next instruction after the block Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 2

Sequence the default Java automatically executes the next instruction unless you use a branching statement Branching if if-else if-else if-else if- - else switch Loop while do-while for Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 3

if Simple selection Do the next statement if test is true or skip it if false Syntax: if (Boolean_Expression) Action if true; //execute only if true next action; //always executed Note the indentation for readability (not compile or execution correctness) Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 4

if if(eggsperbasket < 12) //begin body of the if statement System.out.println( Less than a dozen eggs per basket ); //end body of the if statement totaleggs = numberofeggs * eggsperbasket; System.out.println( You have a total of + totaleggs + eggs. ); The body of the if statement is conditionally executed Statements after the body of the if statement always execute Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 5

Action if true can be either a single Java statement or a set of statements enclosed in braces { }. A set of statements in braces is called a compound statement and can be used anywhere a single statement can be used. All statements between if(eggsperbasket < 12) braces are controlled by if { //begin body of the if statement System.out.println( Less than a dozen... ); costperbasket = 1.1 * costperbasket } //end body of the if statement totaleggs = numberofeggs * eggsperbasket; System.out.println( You have a total of + totaleggs + eggs. ); Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 6

!"if-else Select either one of two options Either do Action1 or Action2, depending on test value Syntax: if (Boolean_Expression) { Action1 //execute only if true } else { Action2//execute only if false } Action3//always executed Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 7

if-else Example with single-statement blocks: if(time < limit) System.out.println( You made it. ); else System.out.println( You missed the deadline. ); Example with compound statements: if(time < limit) { System.out.println( You made it. ); bonus = 100; } else { System.out.println( You missed the deadline. ); bonus = 0; } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 8

#$% Branching: there is more than one choice for the next instruction Which branch is taken depends on a test condition which evaluates to either true or false In general: if test is true then do this, otherwise it is false, do something else Variables (or expressions) that are either true or false are called boolean variables (or expressions) So the value of a boolean variable (or expression) is either true or false boolean is a primitive data type in Java Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 9

$ Boolean expressions can be thought of as test conditions (questions) that are either true or false Often two values are compared For example: Is A greater than B? Is A equal to B? Is A less than or equal to B? etc. A and B can be any data type (or class), but they should be the same data type (or class) Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 10

& Math Notation Name Java Notation Java Examples = equal to == balance == 0 answer = 'y' not equal to!= income tax answer!= 'y' > greater than > income > outgo greater than or equal to >= points >= 60 < less than < pressure < max less than or equal to <= income <= outgo Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 11

'$ Use && to AND two or more conditions» Expression will be true if both parts are true.» A && B will be true if both A and B are true Use to OR two or more conditions» Expression will be true if either part is true, or if both parts are true.» A B will be true if either A or B is true, or if both A and B are true. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 12

'$ Example: write a test to see if B is either 0 or between the values of B and C (B == 0) (A <= B && B < C) In this example the parentheses are not required but are added for clarity» See text (and later slides) for Precedence rules» Note the short-circuit, or lazy, evaluation rules in text (and later in slides)» Use a single & for AND and a single for OR to avoid short-circuit evaluation and force complete evaluation of a boolean expression Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 13

' String == does not do what you may think for String objects» When == is used to test objects (such as String objects) it tests to see if the storage addresses of the two objects are the same are they stored in the same location? more will be said about this later Use.equals method to test if the strings, themselves, are equal String s1 = Mondo ; String s2; s2 = SavitchIn.readLine(); //s1.equals(s2) returns true if the user enters Mondo, false otherwise.equals()is case sensitive Use.equalsIgnoreCase()to ignore case Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 14

()!&'* Use compareto method of String class Uses ASCII lexicographic ordering where all uppercase letters come before all lowercase letters» For example capital 'Z' comes before small 'a'» Convert strings to all uppercase (or all lowercase) to avoid problems s1.compareto(s2)» returns a negative value if s1 comes before s2» returns zero if the two strings are equal» returns a positive value if s2 comes before s1 // Assume s1 and s2 are two string variables // that have been given string values. String uppers1 = s1.toupper(); String uppers2 = s2.toupper(); if (uppers1.compareto(uppers2) < 0) System.out.println(s1 + " precedes " + s2); Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 15

+'if One if statement can have another if statement inside it. These are called nested if statements. Inner statements are indented more than outer statements. if (balance >= 0) if (RATE >= 0) balance = balance + (RATE * balance)/12; else System.out.println("Cannot have negative rate"); else balance = balance OVERDRAWN_PENALTY; The inner statement will be skipped entirely if balance >= 0 is false. outer statement inner statement Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 16

)!!" if-else if-else if- -else One way to handle situations with more than two possibilities Syntax: if(boolean_expression_1) Action_1 else if(boolean_expression_2) Action_2... else if(boolean_expression_n) Action_n else Default_Action Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 17

if-else if-else if- -else if(score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'E'; Note indentation. Even though these are nested if statements, they are all indented the same amount to indicate a multibranch selection. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 18

)!!"switch switch(controlling_expressi on) { case Case_Label: statements break; case Case_Label: statements break; Another way to program multibranch selection Uses Controlling_Expression to decide which way to branch Controlling_Expression must be char, int, short or byte. } default: statements break; Controlling Expression and Case_Label must be same type. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 19

)!!"switch switch(controlling_expressi on) { case Case_Label: statements break; case Case_Label: statements break; } default: statements break; When a break statement is encountered, control goes to the first statement after the switch. break may be omitted Can have any number of cases default case is optional Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 20

switch switch(seatlocationcode) { case 1: System.out.println( Orchestra ); price = 40.00; break; case 2: System.out.println( Mezzanine ); price = 30.00; break; case 3: System.out.println( Balcony ); price = 15.00; break; default: System.out.println( Unknown seat code ); break; } Mezzanine Output if seatlocationcode is 2: Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 21

,"- Structure:» Usually some initialization code» body of loop» loop termination condition Several logical organizations» counting loops» sentinel-controlled loops» infinite loops» minimum of zero or minimum of one iteration Several programming statement variations» while» do-while» for Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 22

while- Syntax: while(boolean_expression) { //body of loop First_Statement;... Last_Statement; } Something in body of loop should eventually cause Boolean_Expression to be false. Initialization statements usually precede the loop. Boolean_Expression is the loop termination condition. The loop will continue executing as long as Boolean_Expression is true. May be either counting or sentinel loop» Good choice for sentinel loop Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 23

!while while (Boolean_Expression) Body Start Evaluate Boolean_Expression true false Execute Body End loop Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 24

while : A Counting Loop Example A loop to sum 10 numbers entered by user int next; //Loop initialization int count = 1; int total =0; while(count <= 10) //Loop termination condition { //Body of loop } next = SavitchIn.readLineInt(); total = total + next; count++; //Loop termination counter Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 25

while" ('- A loop to sum positive integers entered by the user next is the sentinel The loop terminates when the user enters a negative number //Initialization int next = 0; int total = 0; while(next >= 0) //Termination condition { //Body total = total + next; next = SavitchIn.readLineInt(); } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 26

while"(./ Because the first input value read and the test precedes the loop, the body the while loop body may not execute at all //Initialization int next; int total = 0; next = SavitchIn.readLineInt(); while(next >= 0)//Termination condition { //Body } total = total + next; next = SavitchIn.readLineInt(); If the first number the user enters is negative the loop body never executes Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 27

do-while- Syntax do { //body of loop First_Statement;... Last_Statement; } while(boolean_expression); Initialization code may precede loop body Loop test is after loop body so the body must execute at least once (minimum of at least one iteration) May be either counting or sentinel loop» Good choice for sentinel loop Something in body of loop should eventually cause Boolean_Expression to be false. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 28

!do-while do Body while (Boolean_Expression); Start Execute Body Evaluate Boolean_Expression true Execute Body false End loop Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 29

do-while int count = 1; int number = 5; do //Display integers 1 to 5 on one line { System.out.print(count + " "); count++; } while(count <= number); Note that System.out.print() is used and not System.out.println() so the numbers will all be on one line. Output: 1 2 3 4 5 Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 30

for- Good choice for counting loop Initialization, loop test, and loop counter change are part of the syntax Syntax: for(initialization; Boolean_Expression; Update_Action) loop body; Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 31

!for for(initialization; Boolean_Expression; Update_Action) loop body; Start Execute Initialization Evaluate Boolean_Expression true Execute Body false End loop Execute Update_Action Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 32

for Count down from 3 to 1 for(int count = 3; count >= 1; count--) { System.out.print("T = " + count); System.out.println(" and counting"); } System.out.println("Blast off!"); Output: T = 3 and counting T = 2 and counting T = 1 and counting Blast off! Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 33

exit' If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method. n is often used to identify if the program ended normally or abnormally. n is conventionally 0 for normal termination and non-zero for abnormal termination. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 34

exit' System.out.println("Enter e to exit or c to continue"); char userin = SavitchInReadLineChar(); if(userin == 'e') System.exit(0); else if(userin == 'c') { //statements to do work } else { System.out.println("Invalid entry"); //statements to something appropriate } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 35

+'- The body of a loop can have any kind of statements, including another loop. for (line = 0; line < 4; line++) for (star = 0; star < 5; star++) System.out.print('*'); System.out.println(); body of outer loop body of inner loop Each time the outer loop body is executed, the inner loop body will execute 5 times, making a total of 20 times. Output: ***** ***** ***** ***** Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 36

0!!' 1*- The most common loop errors are unintended infinite loops and off-by-one errors in counting loops. Sooner or later everyone writes an unintentional infinite loop» To get out of an unintended infinite loop enter ^C (control-c) Loops should be tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 37

!*%)- Tracing a variable: print out the variable each time through the loop A common technique is to test loop counters and troubleshoot off-by-one and other loop errors. Some systems provide a built-in tracing system that allows you to trace a variable without having to change your program. If no built-in utility is available, insert temporary output statements to print values. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 38

boolean A primitive type Can have expressions, values, constants, and variables just as with any other primitive type Only two values: true and false Can use a boolean variable as the condition in an if statement if (systemsareok) System.out.println("Initiate launch sequence."); else System.out.println("Abort launching sequence"); Using a boolean variable as the condition can make an if statement easier to read by avoiding a complicated expression. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 39

boolean%)(* A boolean expression evaluates to one of the two values true or false. The value of a boolean expression can be assigned to a boolean variable: int number = -5; boolean ispositive; ispositive = (number > 0); if (ispositive) Parentheses are not necessary here. Parentheses are necessary here. System.out.println( positive ); else System.out.println( negative or zero ); There are simpler and easier ways to write this small program, but boolean variables are useful in keeping track of conditions that depend on a number of factors. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 40

)boolean& && (and) Value of A Value of B A && B true true true true false false false true false false false false (or) Value of A Value of B A B true true true true false true false true true false false false! (not) Value of A!A true false false true Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 41

0!'! An example of using precedence rules to see which operators in following expression should be done first: score < min/2 10 score > 90 Division operator has highest precedence of all operators used here so treat it as if it were parenthesized: score < (min/2) 10 score > 90 Subtraction operator has next highest precedence : score < ((min/2) 10) score > 90 The < and > operators have equal precedence and are done in left-toright order : (score < ((min/2) 10)) (score > 90) The last expression is a fully parenthesized expression that is equivalent to the original. It shows the order in which the operators in the original will be evaluated. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 42

0!'!, Highest Precedence First: the unary operators: +, -, ++, --, and! Second: the binary arithmetic operators: *,/,% Third: the binary arithmetic operators: +, - Fourth: the boolean operators: <, >, =<, >= Fifth: the boolean operators: ==,!= Sixth: the boolean operator & Seventh: the boolean operator Eighth: the boolean operator && Ninth: the boolean operator Lowest Precedence Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 43

! Short-circuit evaluation only evaluating as much of a boolean expression as necessary. Example: if ((assign > 0) && ((total/assign) > 60)) System.out.println( Good work ); else System.out.println( Work harder. ); If assign > 0 is false, then the complete expression cannot be true because AND is only true if both operands are true. Java will not evaluate the second part of the expression. Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 44

02 Java selection statements: if, if-else, if-else if, and switch Java repetition (loop) statements: while, do-while, and for Loops can be counter or sentinel controlled Any loop can be written any of the three loop statements, but» while and do-while are good choices for sentinel loops» for is a good choice for counting loops Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 45

03 Unintended infinite loops can be terminated by entering ^C (control-c) The most common loop errors are unintended infinite loops and off-by-one errors in counting loops Branching and loops are controlled by boolean expressions» boolean expressions are either true or false» boolean is a primitive data type in Java exit(n)is a method that terminates a program» n = 0 is the conventional value for normal termination Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 46