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.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
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 –For For Reading for this Lecture, L&L, Part of 5.8.
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.
Recognizing Patterns Counting: continually updating a value by a fixed amount Counting raindrops int dropCount = 0; //Raindrop counter while (dropCount.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.
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.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
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.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while Statements.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow of Control Chapter 3 Flow of control Branching Loops
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Recognizing Patterns Counting: continually updating a value by a fixed amount Counting raindrops int dropCount = 0; //Raindrop counter while (dropCount.
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.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
ITM © Port, Kazman1 ITM 352 Flow-Control: Loops Lecture #8.
CPSC 233 Tutorial 5 February 2 th /3 th, Java Loop Statements A portion of a program that repeats a statement or a group of statements is called.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
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.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Slides by Evan Gallagher
Slides by Evan Gallagher
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Loops.
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Outline Altering flow of control Boolean expressions
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Building Java Programs
Lecture 13 Introduction to High-Level Programming (S&G, §§7.1–7.6)
Announcements/Reminders
Loops and Iteration CS 21a: Introduction to Computing I
Presentation transcript:

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 (FSF). Which could be expanded to GNU’s not UNIX’s not UNIX, which could be expanded to GNU's not UNIX’s not UNIX’s not UNIX, which could be expanded to…….

CS303ELoops2 Iteration – a Basic Operation Example of iteration – building a fence: Move tools and materials to starting point. Install first fence post. Repeat until finished: Move to position of next fence post. Install next fence post. Install fencing between new post and previous post. Loop Body of loop is repeated. Initialization Termination condition

CS303ELoops3 while Loop — Syntax while ( boolean_expression ) statement; or while ( boolean_expression ) {statement;... } Continuation condition Loop body

CS303ELoops4 Syntax and Semantics of while Statements while ( ) while ( ){. } ? statement true false

CS303ELoops5 while Loop for Building Fence Move tools and materials to starting point. Install first fence post. while (not finished) {Move to position of next fence post; Install next fence post; Install fencing between new post and previous post; } Continuation condition

CS303ELoops6 Loops — two basic patterns Count-controlled loop:  Number of iterations is determined before the loop starts.  Counts each iteration in a counter variable.  Stops when the desired number of iterations has been performed. Event-controlled loop:  Before each iteration, checks to see whether some event has occurred.  Continues until that event occurs.  Number of iterations not known beforehand.

CS303ELoops7 Count-controlled loop pattern counter = initialValue; other initialization; while ( counter <= finalValue ) {do computation; increment counter; } Number of iterations is: finalValue – initialValue + 1

CS303ELoops8 Designing Correct Loops  Initialize all variables properly Plan how many iterations, then set the counter and the limit accordingly  Check the logic of the termination condition  Update the loop control variable properly

CS303ELoops9 Count controlled loop example Specification: Sum the squares of the first 10 positive integers. Algorithm: int sum = 0;// initialize sum so far int count = 1;// initialize counter while ( count <= 10 )// 10 = final value {sum = sum + (count * count);// do computation count = count + 1;// increment counter } sumField.setNumber(sum);

CS303ELoops10 Off-by-One Error int counter = 1; while (counter <= 10){ //Executes 10 passes counter++; } int counter = 1; while (counter < 10){ //Executes 9 passes counter++; }

CS303ELoops11 Example – Sum powers of 2 Specification: Sum the first max powers of 2: Algorithm in pseudo-code: 1. Get value for max; 2. Set count to 1, sum to 0, power to 1; 3. While ( count <= max ) {a. Multiply power by 2;// 2, 4, 8,... b. Increment sum by power;// c. Increment count by 1;// 1, 2,..., max } 4. Display sum;

CS303ELoops12 Code – Sum powers of 2 Specification: Sum the first max powers of 2: Code: max = maxField.getNumber(); int count = 1, sum = 0, power = 1; while ( count <= max ) {power = power * 2;// 2, 4, 8,... sum = sum + power;// count = count + 1;// 1, 2,..., max } sumField.setNumber (sum);

CS303ELoops13 Tracing the loop Suppose max = 5. We want to calculate sum = maxcountpowersum Before loop starts:5110 After iteration 1:5222 After iteration 2: After iteration 5:563262

CS303ELoops14 Exercises  Sum the odd numbers from 1 to 10.  Summing from 1 to N is easy. (Thanks to Gauss)

CS303ELoops15 Infinite Loop int counter = 1; while (counter <= 10){// Executes 5 passes counter = counter + 2; } int counter = 1; while (counter != 10){// Runs forever counter = counter + 2; } In general, avoid using != in loop termination conditions.

CS303ELoops16 Event-controlled loop pattern initialization; while ( event has not occurred ) { do work; } Work must eventually cause event to occur. HelloWorld in an Event Driven Programming World while(true){ System.out.print(“Hello World!! “); }

CS303ELoops17 Example – Sum powers of 2 Specification: Sum the powers of 2 up to a power <= limit. Algorithm in pseudo-code: 1. Get value for limit; 2. Set sum to 0, power to 2; 3. While ( power <= limit ) {a. Increment sum by power;// b. Multiply power by 2;// 4, 8, 16,... } 4. Display sum;

CS303ELoops18 Code – Sum powers of 2 limit = inputField.getNumber(); sum = 0; power = 2; while ( power <= limit ) {sum = sum + power;// power = power * 2;// 4, 8, 16,... } outputField.setNumber (sum);

CS303ELoops19 Mixing the two types of loops Specification: Sum the first powers of 2, so long as power <= limit but not more than 10 powers. max = maxField.getNumber(); limit = limitField.getNumber(); sum = 0; power = 2; count = 1; while ( power <= limit && count <= max ) {sum = sum + power;// power = power * 2;// 4, 8, 16,... count = count + 1;// 2, 3, 4,... } outputField.setNumber (sum);

CS303ELoops20 CS 303E Lecture 9: Loops II "An apprentice carpenter may want only a hammer and saw, but a master craftsman employs many precision tools. Computer programming likewise requires sophisticated tools to cope with the complexity of real applications,and only practice with these tools will build skill in their use." - Robert L. Kruse, Data Structures and Program Design

CS303ELoops21 Prime Numbers  Write a program to determine if a given number is prime.  Analysis / Design (algorithm)

CS303ELoops22 Prime Number Implementation

CS303ELoops23 Other Loops  Java provides syntax for two other types of loops  do - while loop  for loop  Any of these could be rewritten as a while loop.

CS303ELoops24 do-while Loop  Syntax do { //body of loop First_Statement;... Last_Statement; } while(Boolean_Expression);  Initialization code may precede loop body

CS303ELoops25 do-while Loop  Loop test is after loop body so the body must execute at least once (minimum of at least one iteration)  May be either count controlled or event controlled loop Good choice for event controlled loop  Something in body of loop should eventually cause Boolean_Expression to be false

CS303ELoops26 do-while Example int count = 1; int number = 10; do //Display integers on one line { System.out.print(count + “, “ ); count++; }while(count <= number); Note System.out.print() is used and not System.out.println() so the numbers will all be on one line

CS303ELoops27 for loop for — A simpler count-controlled loop. The following two loops are equivalent: i = 1; while ( i <= n ) for ( i = 1; i <= n; i = i+1 ) { work i = i + 1; } } Still need while for event-controlled loops and mixed loops (count- and event-controlled). 

CS303ELoops28 for Loop Syntax and Semantics for (initialization statement; termination condition; update statement) loop body statement(s) termination condition loop body statement(s) true false initialization statement update statement

CS303ELoops29 for Example Compute and output first 10 integers and their squares: for (int i = 1; i <= 10; i++) System.out.println(i + " " + i*i + "\n"); initialization statement  int i = 1; termination condition  i <= 10 update statement  i++ (or i = i + 1)

CS303ELoops30 for loop  Initialization, loop test, and loop counter change are part of the syntax. Contrast with while loop.  Execution sequence: 1. Initialization- executes only the first iteration of the loop 2. Boolean_Expression - the loop test 3. loop body - execute only if loop test is true 4. After_Loop_Body - typically changes the loop counter 5. Boolean_Expression - Repeat the loop test (step 2), etc.

CS303ELoops31 Another for Example  Count down from 9 to 0 for(int count = 9; count >= 0; count--) { System.out.print("T = " + count); System.out.println(" and counting"); } System.out.println("Blast off!");

CS303ELoops32 Testing Loops  Check with small values or boundary values (1, 0, -1, limit).  Find a formula for the n-th iteration.  Display a trace if things aren’t working. System.out.println(“x = “ + x + “ y = “ + y); where x and y are the variables of concern.

CS303ELoops33 A Tester Program import BreezyGUI.*; public class Tester{ public static void main(String[] args){ int counter = 1; while (counter <= 10){ System.out.println("Counter = " + counter); counter = counter + 2; } GBFrame.pause(); } A non-GUI program for trying things out quickly.

CS303ELoops34 Text Areas  Another window component. TextArea areaName = addTextArea ( “initial value”, row, col, width, height);  Like a text field, except has scroll bars and can display any width and number of rows of text.  May want width and/or height > 1.  A part of the Java awt, as is Label, TextField, Button. BreezyGUI just makes them easier to use

CS303ELoops35 TextArea methods setText (aString) -- void (no value returned). getText () -- returns String. append (aString) -- void (no value returned). Appends aString to the end of the TextArea. Remember, to go to next line you need \n

CS303ELoops36 Output 10 Numbers to a Text Area TextArea outputArea = addTextArea("", 1,1,2,5); for (int i = 1; i <= 10; i++) outputArea.append(i + "\n");

CS303ELoops37 Output 10 Numbers to a Text Area TextArea outputArea = addTextArea("", 1,1,2,5); for (int i = 1; i <= 10; i++) outputArea.append(i + "\n"); // or String outputStr = ""; for (int i = 1; i <= 10; i++) outputStr = outputStr + i + "\n"; outputArea.setText(outputStr);

CS303ELoops38 Method Format.justify Format is part of the BreezyGUI package Justify data (left, right, or centered) in a field of width characters, with precision decimal places. String justify ( char alignment,// ‘l’ | ‘c’ | ‘r’ type data,// data to be justified int width,// field width int precision)// decimal places (double only) type = String or char or long or double

CS303ELoops39 Format.justify Format.justify(,, ) Format.justify(,,, ) These methods return String objects.

CS303ELoops40 Format.justify Format.justify(,, ) Format.justify(,,, ) Format.justify('l', 34, 4) "34 " Format.justify('r', 34, 4) " 34" Format.justify('c', 34, 4) " 34 " Format.justify('r', , 7, 2) " 34.35"

CS303ELoops41 The Two Versions while (counter <= 20){ sum = sum + counter; output.append(Format.justify('r', counter, 5) + Format.justify('r', sum, 10) + "\n"); counter++; } while (counter <= 20){ sum = sum + counter; output.append(counter + " " + sum + "\n"); counter++; }

CS303ELoops42 Justification of Text Output

CS303ELoops43 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 tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors "Tracing" a variable (outputting its value each time through the loop) is a common technique to test loop counters and troubleshoot off-by-one and other loop errors