CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.

Slides:



Advertisements
Similar presentations
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Flow of Control Part 2: Looping
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Loops and Files.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Looping Yong Choi School of Business CSU, Bakersfield.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
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
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Chapter 5: Control Structures II
JavaScript, Fourth Edition
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Chapter 6 Flow of Control Part 2: Looping. Topics Event-Controlled Loops Using while Looping Techniques Type-Safe Input Using Scanner Constructing Loop.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Lecture 4b Repeating With Loops
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Lecture 6 Repetition Richard Gesick.
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Chapter 5: Control Structures II
Loop Structures.
Java Programming: Guided Learning with Early Objects
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
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.
Lecture 4A Repetition Richard Gesick.
Outline Altering flow of control Boolean expressions
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis

Previous Week’s Topics SWITCH SELECTION STRUCTURE. COMPARING OBJECTS. COMPARING STRINGS. STRING TOKENIZER. CONDITIONAL OPERATOR. 2

New Topics Event-Controlled Loops Using while Type-Safe Input Using Scanner Constructing Loop Conditions Reading a Text File Looping Techniques 3

The Grocery Cashier A grocery cashier's job is to calculate the total costs of the items in the cart. – The cashier starts with a total of $0.00. – The cashier scans an item to get its price and adds the price to the total. – The cashier scans the next item to get its price and adds the price to the total. – When there are no more items to scan, the total is complete. Notice that the cashier is performing the same operations on each item! 4

Looping In computing, we often need to perform the same operations on multiple items. Typically, these tasks follow this pattern: – initialize values (set total to 0) – process items one at a time (add price to total) – report results (report total) The flow of control that programmers use to complete jobs with this pattern is called looping, or repetition. 5

The while Loop The while loop is designed for repeating a set of operations on data items when we don't know how many data items there will be. When we reach the end of the items to process, we will get some signal. (For the grocery cashier, it's the divider bar.) – The end of data items could be indicated by a special input value called a sentinel value or by reaching the end of a file. Receiving the signal is an event; we call this event-controlled looping. 6

while Loop Flow of Control The condition is evaluated. If it is true, we execute the loop. Then the condition is re-evaluated. As long as the condition is true, we execute the loop body. When the condition is false, we skip to the instruction following the loop. 7

Operation of the while Loop If the condition evaluates to true, the loop body is executed, then the condition is re-evaluated As long as the condition evaluates to true, we continue to repeat the loop body The loop body usually "updates the loop condition;" that is, performs some operation that eventually will cause the loop condition to evaluate to false Typically, the loop update will be an attempt to read the next input value, in order to detect the sentinel value or the end of the file 8

while Loop Syntax // initialize variables while ( boolean expression ) { // process data (loop body) } //process the results **Notes: Curly braces are optional if the loop body consists of only one statement Any variable defined within the while loop has block scope and cannot be referenced after the while loop 9

Some Definitions iteration – one execution of the loop body loop update – one or more statements that could cause the loop condition to evaluate to false (and thus end the looping) loop termination condition – the event that causes the loop condition to evaluate to false 10

The Endless Loop If the loop condition never evaluates to false, the loop body is executed continuously, without end. We call this an endless loop or an infinite loop. How can we tell we have an infinite loop? – If the loop body has no output, the computer appears to hang – If the loop body produces output, the output is repeatedly written without end How can we stop an infinite loop? – Abort the program (usually by focusing on the DOS pane and clicking the Ctrl and C buttons together). 11

Avoid putting a semicolon after the condition of a while loop. Doing so creates an empty loop body and could result in an endless loop. This code causes an endless loop: int i = 0; while ( i < 10 ); // empty loop body { i++; // this statement follows the loop } The semicolon indicates an empty loop body; i++ is never executed because it is not part of the loop body, so the condition is always true. Putting a semicolon after the condition 12

Pseudocode for the Grocery Cashier set total to $0.00 reach for first item while item is not the divider bar { get price of item add price to total reach for next item // loop update } // if we get here, the item is the // divider bar output the total price 13

Sentinel-Controlled while Loop initialize variables // priming read read the first data item while ( item is not the sentinel value ) { process the item // update read read the next data item } report the results 14

Example: int count = 0; while ( input != 0 ) // 0 is sentinel value { System.out.print( "Enter an integer > " ); input = scan.nextInt( ); count++; } System.out.println( "Count is " + count ); If the user enters the values 20, 30, 0, the output will be "Count is 3", why?. Sentinel Value Example 15

Example code for Looping int count=0; boolean b=true; while (b) { count++; System.out.println(count); if(count==10) b=false; } This loop counts from What makes the loop stop? 16

Reading from a Text File If the input is stored in a file, the pattern for our loop is different. Reaching the end of the file is our signal that there is no more data. initialize variables while ( not the end of the file ) { read the next data item process the data } report the results 17

Setup for Reading from a File A File class ( java.io package ) constructor A Scanner constructor for reading from a file Example: File inputFile = new File( "input.txt" ); Scanner scan = new Scanner( inputFile ); File ( String pathname ) constructs a File object with the file name pathname Scanner( File file ) creates a Scanner object associated with a file 18

Scanner Class hasNext Method This method detects the end of the input values. The hasNext method eliminates the need for a priming read because the method looks ahead for input. An IOException may be generated if we encounter problems reading the file. Java requires us to acknowledge that these exceptions may be generated. Note that there is an equivaland method called hasNextLine() which returns a boolean and can sense the end of data line by line. Return typeMethod name and argument list boolean hasNext( ) returns true if there is more data to read; returns false when the end of the file is reached. 19

Scanner Class hasNext… Methods Each method returns true if the next token in the input stream can be interpreted as the data type requested, and false otherwise. Return typeMethod name and argument list booleanhasNextInt( ) booleanhasNextDouble( ) booleanhasNextFloat( ) booleanhasNextByte( ) booleanhasNextShort( ) booleanhasNextLong( ) booleanhasNextBoolean( ) booleanhasNext( ) 20

Example Reading From File Suppose the file text.txt has strings that we want to read. import java.io.File; import java.io.IOException; Import java.util.Scanner; public class ReadFile { public static void main(String[] args) { String str; Int count=0; try { File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile); while(scan.hasNext()) { str=scan.next(); System.out. println(str); count++; } } //end of try block of code!!!!!! catch(IOException ioe) { System.out.println(“The file can not be read”); } System.out.println(“The number of strings tokens read is:”+count); } 21

Example Reading From File In the previous example notice that: – The Besides the Scanner class the library classes File and IOException need to be imported. The reason for importing File is so that we can have the system make a connection to the file we are interested at. IOException creates a runtime exception if, for instance, the file does not exists, or it can not be opened for reading for some reason. The term exception means that the system does not crash if something went wrong and instead it gracefully terminates and gives us a message about the error (exception) that took place. An example of that is trying to divide a number buy zero. – The try and catch keywords need to be used to catch a possible exception IOException. Exception occurs if something goes wrong with the execution of the program. In this case the opening of the File for reading. 22

Example Reading From File – We iterate through the file and we keep reading Strings separated by space as long as there are Strings to be read. – We also count the number of String s we read. When we get out of the loop we should read the value of count. – Notice that if for some reason our attempt to open the file for reading fails, the catch block of code will be executed. try { code that can fail goes here } catch(IOException io){ System.out.println(“Something went wrong!”); } The catch part is executed only if there is a failure inside the try. 23

Looping Techniques There are standard patterns and techniques for performing common programming operations: – Accumulation – Counting Items – Finding an Average – Finding Maximum or Minimum Values 24

Accumulation Calculating a total of input values Approach: the running total – We start by initializing a total variable to 0 – Each time we read a value, we add the value to the total – When we have no more values to read, the total is complete Note that this is the same pattern used by the grocery cashier. 25

Accumulation Pseudocode set total to 0 // very important! read a number // priming read while ( number is not the sentinel value ) { add the number to total read the next number // update read } output the total 26

Counting Items Approach: the running count – We start by initializing a count variable to 0. – Each time we read a value, we check whether that value meets the criteria as something we want to count. If so, we increment the count variable by 1. – When we are finishing reading values, the count is complete. 27

Counting Items Pseudocode set count to 0 // very important!! read input // priming read while ( input is not the sentinel value ) { if ( input is what we want to count ) add 1 to count read the next input // update read } output count 28

Calculating an Average Approach: combine accumulation and counting We start by initializing a total variable and a count variable to 0 Each time we read an item, we add its value to the total variable and increment the count variable When we have no more items to read, we calculate the average by dividing the total by the count 29

Calculating an Average Pseudocode set total to 0 set count to 0 read a number while ( number is not the sentinel value ) { add the number to total add 1 to the count read the next number } set average to total / count output the average 30

Finding Maximum/Minimum Values Approach: the running maximum or minimum For the maximum (minimum is similar): – Read the first item and save its value as the current maximum – Each time we read a new value, we compare it to the current maximum If the new value is greater than the current maximum, we replace the current maximum with the new value – When we have no more items to read, the current maximum is the maximum for all values 31

Finding Maximum Value Pseudocode (Reading From a File) read a number make that number the maximum while ( there is another number to read ) { read the next number if ( number > maximum ) { set maximum to number } output the maximum 32

Study Guide Read chapter 6 – Sections: 6.1, 6.2, 6.3, 6.4 but not