1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 7 - Iteration.

Slides:



Advertisements
Similar presentations
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Advertisements

CS0007: Introduction to Computer Programming
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Chapter 6 Iteration Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
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.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Datalogi A 5: 6/10. while Loops Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement; Most.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
Chapter 6  Iteration 1 Chapter 6 Iteration. Chapter 6  Iteration 2 Chapter Goals  To be able to program loops with while and for (sometimes do ) statements.
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 Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Introduction to Computer Programming in c
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Repetition Statements
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Chapter 5: Control Structures II
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Selected Topics From Chapter 6 Iteration
Chapter 5: Control Structures II
LOOPS.
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Chapter 7 Iteration.
Looping and Repetition
Presentation transcript:

1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 7 - Iteration

2 Lecture Outline Programming loops (iteration) Simple GUI animation Understand common loop errors Nested loops Processing input File input/output Random numbers and simulations CSC120 — Berry College — Fall 2005

3 Cannonball Exercise P7.3 Cannonball.java CannonTester.java

4 while Loop Looping = Iteration = Repetition while ( condition ) statement while statement repeatedly executes a block of code as long as condition is true double curTime = 0.00; while ( curTime <= 20.0 ) { ball.updatePosition( deltaT ); curTime += deltaT; }

5 Counting Program int count, number, sum; System.out.println( "Enter a number to count up to: " ); Scanner in = new Scanner( System.in ); number = in.nextInt(); count = 1; sum = 0; while ( count <= number ) { System.out.println( count ); sum += count; count++; } System.out.println(); System.out.println( "The sum is: " + sum ); Loop body Termination test Initialization

6 Side Topic: Simple GUI Animation Basic idea: Add a Timer object to your component class Every time the timer goes off (e.g. 10 msec) update the display Imports needed import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.Timer; CannonballComponent.java CannonballViewer.java

7 GUI Animation Skeleton public class ComponentName extends JComponent implements ActionListener {... /** Starts the timer going by constructing a Timer object with the frequency (in milliseconds) of Timer activations and the object ('this') that will be handling the Timer events */ public void animate() { timer = new Timer( (int)Math.round(deltaT * 1000), this ); timer.start(); } /** Processes a Timer activation event */ public void actionPerformed( ActionEvent e ) { // Code to update the state of the object // should go here... repaint(); // repaint the component on the screen } Timer timer; // timer instance variable... // other instance variables (fields) }

8 Infinite Loops count = 1; sum = 0; while ( count <= number ) { System.out.println( count ); sum += count; } // (two errors in this code?) count = number; // count down from number sum = 0; while ( count <= number ) { System.out.println( count ); sum += count; count++; } Stop a running program using ‘Ctrl’+ ‘c’ keys

9 count = 1; sum = 0; while ( count < number ) { count++; System.out.println( count ); sum += count; } Off-by-One Errors Common type of error when programming loops Work through simple test cases to avoid these errors Common issues: Should variable start at 0 or 1 ? Should test condition be < or <= ? Where should the loop variable be updated? Note: when processing strings, loops often start at 0 and use <

10 do Loop Executes the loop body at least once do statement while ( condition ); Common use: Validating input double value; do { System.out.print( "Please enter a positive number: ” ); value = in.nextDouble(); } while (value <= 0);...

11 Replacing do with while Introduce a boolean control variable double value; boolean done = false; while ( !done ) { System.out.print( "Please enter a positive number: ” ); value = in.nextDouble(); if ( value > 0 ) done = true; }...

12 A Common Loop Idiom i = start; while ( i <= end ) {... i++; } Special syntax supports this idiom for ( i = start; i <= end; i++ ) {... }

13 for Loop for ( initialization ; condition ; update ) statement Use a for loop when a variable runs from a starting to end value with constant increment or decrement Easy to abuse for notation – any expressions can be put in the header for ( rate = 5; years-- > 0; System.out.print(balance) )...

14 How for Loops Work for ( initialization ; condition ; update ) body Evaluate initialization Evaluate condition Execute body Evaluate update End loop truefalse

15 for Loops: Common Errors Extra semicolon sum = 0; for ( i = 1; i <= 10; i++ ); sum = sum + i; System.out.println(sum); Missing semicolon for (years = 1; (balance = balance + balance * rate / 100) < targetBalance; years++) System.out.println(years); Using != condition instead of <= for ( i = 1; i != 10; i+=2 )...

16 Variable Scope in for Loops Scope: the area of code in which an identifier (name) is defined/can be used Possible to declare a new variable in the header of a for loop - only has scope within the loop for ( int i = 1; i <= n; i++ ) {... } // i is no longer defined here

17 Commas in for Statements Header of a for loop can contain multiple initializations/updates, separated by commas For example, this code: product = 1; for ( n = 1; n <= 10; n++ ) product = product * n; Can be rewritten as: for ( n=1, product=1; n<=10; product=product*n, n++ ) ; Considered ‘clever’ but not necessarily good coding practice

18 Fibonacci Numbers Write a program to compute the n’th Fibonacci number f1 = 1; f2 = 1; cur = 3; while ( cur <= n ) { long fnew = f1 + f2; f1 = f2; f2 = fnew; cur++; } System.out.println( n + "th Fibonnaci number is: " + f2 ); f1 = 1; f2 = 1; for ( cur = 3; cur <= n; cur++ ) { long fnew = f1 + f2; f1 = f2; f2 = fnew; }

19 Nested Loops Often one loop may be nested (contained) in another Typical example: Printing table of rows and columns Write a program to print out a triangular shape, given a maximum width (e.g. 5): [] [][] [][][] [][][][] [][][][][]

20 Nested Loops Pythagorean Triples Set of integer values such that Write a program to find all such triples, where the side lengths are less than 100 PythagTriples.java sideA sideB hyp

21 Processing Sentinel Values Sentinel: value that is not valid input and indicates the end of input 0 or -1 are not always good sentinel values Enter value, Q to quit: 1 Enter value, Q to quit: 2 Enter value, Q to quit: 3 Enter value, Q to quit: 4 Enter value, Q to quit: Q Average = 2.5 Maximum = 4.0 DataSet.java

22 Loop and a Half Sometimes the termination condition can only be checked in the middle of a loop Then, introduce a boolean variable to control the loop boolean done = false; while ( !done ) { System.out.print( "Enter value, Q to quit: " ); String input = in.next(); if ( input.equalsIgnoreCase( "Q" ) ) done = true; else { double x = Double.parseDouble( input ); data.add(x); } System.out.println("Average = " + data.getAverage()); System.out.println("Maximum = " + data.getMaximum());

23 break Statement Used to break out of a switch statement Also used to exit (immediately) a while, for, or do loop See Advanced Topic 7.4 (pg ) while ( true ) { System.out.print( "Enter value, Q to quit: " ); String input = in.next(); if ( input.equalsIgnoreCase( "Q" ) ) break; double x = Double.parseDouble( input ); data.add(x); }

24 File Input/Output (Section 16.1) Two ways of storing data in files Text format – human readable sequence of characters Convenient for humans Binary format – bytes of data More compact and efficient We will use Scanner class to read input from text files PrintWriter class to write output to text files

25 Reading Text File First construct FileReader object with the name of the input file Then use it to construct a Scanner object Use the Scanner object for input just as if it was keyboard input Use next, nextLine, nextInt, nextDouble methods FileReader reader = new FileReader( "input.txt" ); Scanner in = new Scanner( reader ); After done reading input, call the close method on the FileReader object

26 Writing Text File Construct a PrintWriter object with the name of the output file Use print, println, printf methods PrintWriter out = new PrintWriter( "output.txt" ); Close the file when done Otherwise not all output may be written to the file out.close();

27 Skeleton Code for File Input/Output // import necessary classes import java.io.IOException; import java.io.PrintWriter; import java.io.FileReader; import java.util.Scanner; public class... { public... { // method... try { // Do file input/output stuff here //... } catch ( IOException exc ) { System.out.println( "Error processing file: " + exc ); }... } LineNumberer.java

28 Random Numbers and Simulation In a simulation, you repeatedly generate random numbers and use them to simulate an activity Random generator = new Random(); int n = generator.nextInt(a); // 0 <= n < a double x = generator.nextDouble(); // 0 <= x < 1

29 Random Numbers Random class ( java.util package) provides a (pseudo)random number generator Produces long sequences of non-repeating numbers that behave like a random sequence Two useful methods nextInt(n) – returns ‘random’ integer between 0 (inclusive) and n (exclusive) nextDouble() – returns ‘random’ floating-point number between 0.0 (inclusive) and 1.0 (exclusive) Die.java DieTester.java

30 Buffon Needle Experiment

31 Needle Position When does a needle fall on a line? Needle length = 1in, distance between lines = 2in Generate random y low between 0 and 2 Generate random angle α between 0 and 180 degrees y high = y low + sin( α) Hit if y high ≥ 2 Needle.java NeedleTester.java