Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Advertisements

Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Chapter Day 14. © 2007 Pearson Addison-Wesley. All rights reserved5-2 Agenda Day 14 Problem set 3 posted  10 problems from chapters 5 & 6  Due in 11.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Chapter Day 12. © 2007 Pearson Addison-Wesley. All rights reserved5-2 Agenda Day 12 Problem set corrected  1 A, 2 B’s and 1 D Starting Late and not turning.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 4: Loops and Files
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Chapter 5 Loops.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Control Structures II
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Outline The if Statement and Conditions Other Conditional.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Repetition Statements b Repetition statements allow us to execute a statement multiple times repetitively b They are often simply referred to as loops.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
COS 312 DAY 5 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Posted – Due Feb 22 prior to class – Any issues? Assignment 3 will be posted soon Capstones.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Conditionals and Loops
Chapter 6 More Conditionals and Loops
Outline Boolean Expressions The if Statement Comparing Data
Debugging October 3, 2007 ComS 207: Programming I (in Java)
Outline Altering flow of control Boolean expressions
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
What output is produced by the following fragment?
Debugging October 4, 2006 ComS 207: Programming I (in Java)
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Chap 7. Advanced Control Statements in Java
CSCI 1100/1202 February 6, 2002.
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
CprE 185: Intro to Problem Solving (using C)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

Chapter 5 – Part 3 Conditionals and Loops

© 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Other Repetition Statements Iterators

© 2004 Pearson Addison-Wesley. All rights reserved3/19 The do Statement A do statement has the following syntax: do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

© 2004 Pearson Addison-Wesley. All rights reserved4/19 Logic of a do Loop true condition evaluated statement false Note: no ‘pretest.’ Statement will at least be executed on time!

© 2004 Pearson Addison-Wesley. All rights reserved5/19 The do Statement An example of a do loop: The body of a do loop executes at least once See ReverseNumber.javaReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5);

© 2004 Pearson Addison-Wesley. All rights reserved6/19 Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop

© 2004 Pearson Addison-Wesley. All rights reserved7/19 The for Statement – VIP! A for statement has the following syntax: Remember: every loop has some kind of initialization, test to continue/end the loop, and a body of the loop. for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration

© 2004 Pearson Addison-Wesley. All rights reserved8/19 Logic of a for loop statement true condition evaluated false increment initialization Does initializing, pretest, increment and posttest …..

© 2004 Pearson Addison-Wesley. All rights reserved9/19 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } Know how to write the same functionality in ALL loops. For example, I will give you an exercise and require you to write the solution using a do…while, while loop, and a for loop.

© 2004 Pearson Addison-Wesley. All rights reserved10/19 The for Statement An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

© 2004 Pearson Addison-Wesley. All rights reserved11/19 The for Statement The increment section can perform any calculation A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance Used a lot where ‘counting’ is needed See Multiples.javaMultiples.java See Stars.java next slide.Stars.java for (int num=100; num > 0; num -= 5) System.out.println (num);

© 2004 Pearson Addison-Wesley. All rights reserved12/19 public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print (“*”); System.out.println(); } // end for } // end main() } // end class Here we have an example of nested-for loops.

© 2004 Pearson Addison-Wesley. All rights reserved13/19 The for Statement  Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed  (This had better be performed outside / prior to the loop) If the condition is left out, it is always considered to be true, and therefore creates an infinite loop  But the loop must terminate. So some specific code within the loop had better constitute a test so that the loop may terminate. If the increment is left out, no increment operation is performed  Again, if left out, something within the body of the loop had better increment or adjust the increment/decrement counter.  You may omit these at your own peril. It is actually okay, but you’d better be VERY careful!!!!!

© 2004 Pearson Addison-Wesley. All rights reserved14/19 Iterators An iterator is an object that allows you to process a collection of items one at a time It lets you step through each item in turn and process it as needed hasNext methodAn iterator object has a hasNext method that returns true if there is at least one more item to process The next method returns the next item Iterator objects are defined using the Iterator interface, which is discussed further in Chapter 6

© 2004 Pearson Addison-Wesley. All rights reserved15/19 Iterators Several classes in the Java standard class library are iterators The Scanner class is an iterator  the hasNext method returns true if there is more data to be scanned  the next method returns the next scanned token as a string The Scanner class also has variations on the hasNext method for specific data types (such as hasNextInt ) Essentially, an iterator is an object that points to a collection of objects. Within the iterator are methods that the service provider provides, such as hasNext(), next() and others as appropriate. The iterator object’s methods allow a client to process a collection of objects without getting into the collection methods themselves… That is, the iterator’s methods are data independent. Will explain more later. Very useful for processing arrays, linked lists, and more.

© 2004 Pearson Addison-Wesley. All rights reserved16/19 Iterators – I couldn’t resist… Example: I have stored a collection of numbers in an ‘array.’ I want to add all of them up or develop the ‘average.’ So, I must first see if there is another number, then fetch it, then add it, and repeat until there are no more numbers. To do this, I must initialize a variable to accumulate the sum and then do all above. If an iterator is defined on this collection of numbers, I don’t have to worry about if there are more, indexing to point to the next one, fetch it, add it and continue. I only need to determine if there are more (hasNext()) and issue a next() and add. I don’t have to worry about what the data looks like (integers, floats, objects, etc.). The iterator, properly designed, will accommodate all this for me. Sample: int [ ] myGrades = {92, 85, 72, 98, 80}; Interpret as: myGrades [0] = 92; myGrades [1] = 85, etc…..

© 2004 Pearson Addison-Wesley. All rights reserved17/19 Iterators The fact that a Scanner is an iterator is particularly helpful when reading input from a file Suppose we wanted to read and process a list of URLs stored in a file One scanner can be set up to read each line of the input until the end of the file is encountered Another scanner can be set up for each URL to process each part of the path See URLDissector.java on the next slide.URLDissector.java

© 2004 Pearson Addison-Wesley. All rights reserved18/19 // URLDissector.java Author: Lewis/Loftus import java.util.Scanner; import java.io.*; public class URLDissector { // Reads urls from a file and prints their path components. public static void main (String[] args) throws IOException { String url; Scanner fileScan, urlScan; // Here we have two Scanner references to objects to be created. // so far, we’ve only read from the keyboard; here, we read from a file fileScan = new Scanner (new File ("urls.input")); // creates Scnner object which points to file named urls.input… // Read and process each line of the file while (fileScan.hasNext()) // as long as there is one more ‘record’, we will continue… // hasNext() is an inherited method that all Scanner objects have. This is how the Scanner //class is defined – it already contains these methods… { url = fileScan.nextLine(); // retrieves next string from urls.inp file. System.out.println ("URL: " + url); // prints it. urlScan = new Scanner (url); // Here we create new Scanner object; feed it String retrieved // from the most recent fileScan (three lines above) urlScan.useDelimiter("/"); // Print each part of the url while (urlScan.hasNext()) System.out.println (" " + urlScan.next()); System.out.println(); }// end outer while } // end main() } //end class URLDissector much more later….

© 2004 Pearson Addison-Wesley. All rights reserved19/19 Iterators and for Loops Recall that an iterator is an object that allows you to process each item in a collection A variant of the for loop simplifies the repetitive processing the items For example, if BookList is an iterator that manages Book objects, the following loop will print each book: array of Books for (Book myBook : BookList) System.out.println (myBook); Very important concept. Will hit this harder later. But learn the basics here.

© 2004 Pearson Addison-Wesley. All rights reserved20/19 Iterators and for Loops This style of for loop can be read "for each Book in BookList, …" Therefore the iterator version of the for loop is sometimes referred to as the foreach loop It eliminates the need to call the hasNext and next methods explicitly It also will be helpful when processing arrays, which are discussed in Chapter 7

© 2004 Pearson Addison-Wesley. All rights reserved21/19 Questions I like to ask… Write a loop to add the first 100 positive integers (1-100) using  A while loop  A for loop  A do…while loop Do all loops test first? If so, agree; if not, who?? Which loop is best for testing some general boolean condition? Which loop is best for counting? Which loop will always execute first before testing?