Announcements/Reminders

Slides:



Advertisements
Similar presentations
Branching Loops exit(n) method Boolean data type and expressions
Advertisements

Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
ITM352 Loops Lecture #6. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule”
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
CS303ELoops1 CS 303E Lecture 8: Loops Self-referentially, short for GNU's not UNIX, a Unix-compatible software system developed by the Free Software Foundation.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
COMP 110: Introduction to Programming Tyler Johnson Feb 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Chapter 3 Edited by JJ Shepherd
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
ITM 352 Flow-Control: if and switch. ITM © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.
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
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Introduction To Scientific Programming Chapter 3.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type.
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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Lecture 3 Selection Statements
Chapter 4 – C Program Control
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
The switch Statement, and Introduction to Looping
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Loop Structures.
ITM 352 Flow-Control: if and switch
ITM 352 Flow-Control: Loops
Branching Loops exit(n) method Boolean data type and expressions
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Control Structures – Selection
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Selection (if-then-else)
3 Control Statements:.
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 4: Control Structures I (Selection)
Web Programming– UFCFB Lecture 20
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Chap 7. Advanced Control Statements in Java
Announcements Program 1 due noon Lab 1 due noon
Controlling Program Flow
Chapter 3 Flow of Control Loops in Java.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Announcements/Reminders Newsgroup: news.purdue.edu – purdue.class.cs180 Exam 1: Thursday Feb. 10, 7:00-8:00 pm If you have a conflict, contact KC VanZandt at least a week before! Covers chapters 1-4 Project 2 released: due Thursday, Feb. 3 at 10:30 pm. Start early

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

Programming Tip Always enclose the body of an if/loop statement in braces, even if there is only one statement. Prevents bugs when adding code later. if(eggsPerBasket < 12) System.out.println(“Less than a dozen ...”); costPerBasket = 1.1 * costPerBasket; // Above line always executed despite indentation totalEggs = numberOfEggs * eggsPerBasket; System.out.println(“You have a total of “ + totalEggs + “ eggs.”);

All statements between braces are controlled by if Multiple Statements 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 braces are controlled by if if(eggsPerBasket < 12) { //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.”);

Nested if Statements if (balance >= 0) { if (RATE >= 0) balance = balance + (RATE * balance)/12; } else System.out.println("Cannot have negative rate"); balance = balance – OVERDRAWN_PENALTY;

if-else if-else if-…-else Example if (score >= 90) grade = 'A'; if (score >= 80) grade = 'B'; if (score >= 70) grade = 'C'; if (score >= 60) grade = 'D'; else grade = 'F'; 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 = 'F'; What would be the results with a score of 93?

Multibranch selection: switch switch(Controlling_Expression) { case Case_Label: statements … break; default: } Another way to program multibranch selection (instead of if-else if-else...) Similar to if-else if-else: at each case, it tests to see if Case_Label == Controlling_Expression See next slide for example

switch(seatLocationCode) { case 1: System.out.println(“Orchestra”); price = 40.00; break; case 2: System.out.println(“Mezzanine”); price = 30.00; default: System.out.println(“Unknown seat code”); } if(seatLocationCode == 1) { System.out.println(“Orchestra”); price = 40.00; } else if (seatLocationCode == 2) System.out.println(“Mezzanine”); price = 30.00; else { System.out.println(“Unknown seat code”);

Additional switch Example switch (gender) { case ‘f’: case ‘F’: System.out.println(“Female”); break; case ‘m’: case ‘M’: System.out.println(“Male”); default: System.out.println(“Invalid gender.”); }

Switch: leaving out the break switch (grade) { case ‘A’: System.out.println(“You got an A”); case ‘B’: System.out.println(“You got a B”); case ‘C’: System.out.println(“You got a C”); case ‘D’: System.out.println(“You got a D”); case ‘F’: System.out.println(“You got an F”); }

Switch: Output If grade was ‘A’: You got an A You got a B You got a C You got a D You got an F

Switch: correct way switch (grade) { case ‘A’: System.out.println(“You got an A”); break; case ‘B’: System.out.println(“You got a B”); case ‘C’: System.out.println(“You got a C”); case ‘D’: System.out.println(“You got a D”); case ‘F’: System.out.println(“You got an F”); }

Repetition: Loops 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

while Loop Syntax: while(Boolean_Expression) { //body of loop First_Statement; ... Last_Statement; } 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 Something in body of loop should eventually cause Boolean_Expression to be false.

Semantics of the while Statement while (Boolean_Expression) Body Start Evaluate Boolean_Expression End loop false Execute Body true

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) //Termination condition { //Body of loop next = SavitchIn.readLineInt(); total = total + next; count++; //Loop termination counter }

while: A Minimum of Zero Iterations Because the first input value read and the test precedes the loop, the body of the while loop body may not execute at all //Initialization int next; int total = 0; next = SavitchIn.readLineInt(); while(next >= 0) //Termination condition { total = total + next; } If the first number the user enters is negative, the loop body never executes

do-while Loop 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.

Semantics of the do-while Statement Body while (Boolean_Expression); Start Evaluate Boolean_Expression End loop false Execute Body true

do-while Example 1 2 3 4 5 int count = 1; int number = 5; do //Display integers 1 to 5 on one line { System.out.print(count + " "); count++; } while(count <= number); Output: Note that System.out.print() is used and not System.out.println() so the numbers will all be on one line. 1 2 3 4 5

for Loop 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;

Semantics of the for Statement for(Initialization; Boolean_Expression; Update_Action) loop body; Start Evaluate Boolean_Expression End loop false Execute Body true Execute Initialization Execute Update_Action A for loop can have zero iterations if the Boolean_Expression is initially false!

for Example 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!"); T = 3 and counting T = 2 and counting T = 1 and counting Blast off! Output:

Nested Loops The body of a loop can have any kind of statements, including another loop. Each time the outer loop body is executed, the inner loop body will execute 5 times, making a total of 20 times. body of outer loop for (line = 0; line < 4; line++) { for (star = 0; star < 5; star++) System.out.print('*'); System.out.println(); } body of inner loop ***** Output:

Some Practical Considerations When Using Loops 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.

Tracing a Variable in a Loop 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.

The Type 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 Using a boolean variable as the condition can make an if statement easier to read by avoiding a complicated expression. if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launching sequence");

boolean Variables in Assignments 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) 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. Parentheses are not necessary here. Parentheses are necessary here.

Truth Tables for boolean Operators && (and) || (or) Value of A Value of B A && B true true true true false false false true false false false false Value of A Value of B A || B true true true true false true false true true false false false Value of A !A true false false true ! (not)

Precedence 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-to-right 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.

Precedence Rules 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

Short-Circuit Evaluation Short-circuit evaluation—only evaluating as much of a boolean expression as necessary. Example: 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. if ((assign > 0) && ((total/assign) > 60)) System.out.println(“Good work”); else System.out.println(“Work harder.”);

No Short-Circuit Evaluation The & and | operators do not short-circuit This could result in division by zero – a run-time error! if ((assign > 0) & ((total/assign) > 60)) System.out.println(“Good work”); else System.out.println(“Work harder.”);

No Short-Circuit Evalutation When would you want short-circuit evaluation? Consider the following code: Above, if x.evaluate() is false, then y.reassign() is never run. To ensure that y.reassign() will be executed, use: (x.evaluate() && y.reassign()) (x.evaluate() & y.reassign())

Summary Part 1 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

Summary Part 2 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