Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Similar documents
Arrays. Loops + arrays: challenge problem. Arrays (II) An array is a set of variables of the same type accessed by their index.

STUDENT LESSON A12 Iterations

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Java Coding 3. Over & over again!

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example: Monte Carlo Simulation 1

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

CSE 114 Computer Science I

Top-Down Program Development

Loops (while and for)

CS111: PROGRAMMING LANGUAGE II

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Loops. CSE 114, Computer Science 1 Stony Brook University

Controls Structure for Repetition

CMPT 125: Lecture 4 Conditionals and Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Repetition, Looping. While Loop

Repetition Structures

Bjarne Stroustrup. creator of C++

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Declaring and ini,alizing 2D arrays

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Claremont McKenna College Computer Science

Question: Total Points: Score:

Introduction to the Java Basics: Control Flow Statements

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Chapter 17. Iteration The while Statement

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Iteration statements - Loops

CSC 1051 Data Structures and Algorithms I

Control Statements: Part 1

Full file at

Chapter Goals. Contents LOOPS

Flow of Control: Loops. Chapter 4

Last Class. While loops Infinite loops Loop counters Iterations

method method public class Temperature { public static void main(string[] args) { // your code here } new

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Chapter 4: Control structures. Repetition

Array. Prepared By - Rifat Shahriyar

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

COMP 202 Java in one week

Introduction to Java & Fundamental Data Types

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

Scope of this lecture. Repetition For loops While loops

Repetition. Chapter 6

Chapter 4: Control structures

Introduction to Software Development (ISD) Week 3

Repetition. Chapter 6

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

LOOPS. Repetition using the while statement

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Ch. 6. User-Defined Methods

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Loops. Repeat after me

Chapter 3. Selections

CS111: PROGRAMMING LANGUAGE II

Handout 4 Conditionals. Boolean Expressions.

COMP 110 Programming Exercise: Simulation of the Game of Craps

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

AP CS Unit 3: Control Structures Notes

COMP-202 Unit 4: Programming with Iterations

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Lecture 14. 'for' loops and Arrays

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Condi(onals and Loops

Conditionals, Loops, and Style

The for Loop. Lesson 11

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

CP122 CS I. Iteration

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

CS1150 Principles of Computer Science Loops (Part II)

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Repetition, Looping CS101

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Exercise (Revisited)

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Chapter 7 User-Defined Methods. Chapter Objectives

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Question: Total Points: Score:

Object Oriented Programming. Java-Lecture 6 - Arrays

Control Structures: if and while A C S L E C T U R E 4

Transcription:

Loops! Flow of Control: Loops (Savitch, Chapter 4) TOPICS while Loops do while Loops for Loops break Statement continue Statement CS 160, Fall Semester 2014 2 An Example while Loop Step- by- step int count = 1; int sum = 0; while (count < 5) sum += count; count++; What exactly does this code do? int count = 1; int sum = 0; while (count < 5) sum += count; count++; Code begins count = 1, sum = 0 False, True true, again, enter exit loop (count re-enter 5, loop sum 10) Bottom of loop: count = 2, 3, 4, 5, sum = 36 10 CS 160, Fall Semester 2014 3 CS 160, Fall Semester 2014 4 1

More formally: while Loops Echo Example Program while (condition) body Repeatedly executes as long as the condition evaluates to true body of the loop is a single statement or muliple statements within The condiion is tested before the body is executed, so loop may execute zero Imes This is called a pre- test loop CS 160, Fall Semester 2014 5 import java.u3l.scanner; public class Foo public sta3c void main(string[] args) Scanner in_str = new Scanner(System.in); String user_string = in_str.next(); while (!user_string.equals("quit")) System.out.println(user_string); user_string = in_str.next(); CS 160, Fall Semester 2014 6 Echo Example: Notes Echo Example: QuesIons import java.util.scanner; is necessary to use a Scanner. Problem: Without it, Eclipse will tell you it cannot resolve the Scanner class. SoluIon: ctrl- shit- o will import needed classes. Remember that! means not in Java. Note the indentaion: the body of the while loop is indented relaive to the surrounding code. How many Imes will the loop body execute? Undetermined: it will keep execuing unil the user types quit What is the fewest number of Imes the loop body could execute? Zero CS 160, Fall Semester 2014 7 CS 160, Fall Semester 2014 8 2

Warning! An infinite loop will occur if the condiion never becomes false. Example: int count = 1; int sum = 0; while (count <= 5) sum += count; count never gets updated always = 1 What if my program gets caught in an infinite loop? You will need to kill your program This is operaing system specific Make your life easier: run your program in the debugger! In Eclipse, select debug instead of run. It will offer to take you to the debug view. Use the red buaon to kill the program. Benefit: Run program step- by- step (F5). CS 160, Fall Semester 2014 9 CS 160, Fall Semester 2014 10 Another example: find divisors Notes on divisor example (1) public class foo public sta3c void main(string[] args) int number = Integer.parseInt(args[0]); int divisor = 2; while (divisor < number ) if ((number % divisor) == 0) System.out.print(divisor + " "); divisor = divisor + 1; The main method takes an array of strings (called arguments or args). args[0] is the first string passed to the method args[1] would be the second string args.length tells you how many strings there are More about arrays later CS 160, Fall Semester 2014 11 CS 160, Fall Semester 2014 12 3

Notes on divisor example (2) Divisor example quesions Integer is an object class in Java. It has a method that reads a string and returns the integer it contains. Hence Integer.parseInt(args[0]); We append a space to the number when prining, so that the numbers are separated in the output. If the argument is 32, how many Imes will the loop body be executed? 30 If the argument is 2, how many Imes will the loop body be executed? 0 If the argument is - 5, what will happen? The loop body will run 0 Imes CS 160, Fall Semester 2014 13 CS 160, Fall Semester 2014 14 Example Program to Remove Vowels public class Foo public sta3c void main(string[] args) String str = args[0]; int ctr = 0; while (ctr < str.length()) switch(str.charat(ctr)) case 'a' : case 'e' : case 'i' : case 'o' : case 'u' : break; default : System.out.print(str.charAt(ctr)); ctr = ctr + 1; CS 160, Fall Semester 2014 15 Remove Vowels: Notes The charat(i) method of String returns the ith character. Zero- based: 0, 1, 2, The length() method of String returns the number of characters in the string. CS 160, Fall Semester 2014 16 4

Remove Vowels: QuesIons for Loop If the input is Programming : How many Imes will the loop body execute? 11 What will the output be? Prgrmmng If the input is Java : How many Imes will the loop body execute? Exercise What will the output be? Exercise It is common to iterate counter number of Imes. counter might be a numeric bound As in the divisor example counter might be the length of a string or array As in the remove vowels example A for loop gives you a mechanism to specify this explicitly CS 160, Fall Semester 2014 17 CS 160, Fall Semester 2014 18 for Loop: Syntax for Loop: Order for (initialization; condition; update) body A pre- test loop Assignment that: statement IniIalizes a loop variable Boolean Executes body of loop zero or more Imes expression Repeatedly: Tests the condiion Executes the body if condiion is true, else exits loop Updates the loop variable Assignment statement for( iniializaion ; booleanexpression ; incrementer ) statements; CS 160, Fall Semester 2014 19 CS 160, Fall Semester 2014 20 5

Example int sum = 0; for(int count=1; count <= 5; count++) sum +=count; Mapping between for and while while loop version initialization; while (condition) statement; update; for loop version for (initialization; condition; update ) statement; CS 160, Fall Semester 2014 21 CS 160, Fall Semester 2014 22 Temperature Conversion Program System.out.println( \tdegrees C\tDEGREES F ); for (int cent = 50; cent <= 100; cent++) double fahr = (9.0 / 5.0) * cent + 32.0; System.out.print( \t + cent); System.out.println( \t + fahr); Example: What does this do? String s = nice string ; for (int i=s.length()-1; i>= 0; i--) System.out.print(s.charAt(i)); What happens if we use println instead of print? Why the -1? CS 160, Fall Semester 2014 23 CS 160, Fall Semester 2014 24 6

Variants on the for Loop do while Statement MulIple variables in for loop int x = 1; for( int lo = 0, hi = 10; lo < hi; lo++, hi- - ) System.out.println( x++ ); 1 2 3 4 5 do body while (condition); Not all parts to the for loop String s = Javarules ; int i = s.length( ) 1; for ( ; i>=0; ) System.out.print( s.charat(i--) ); seluravaj post- test loop: always executes the loop body at least once Executes again as long as its condiion is true are required ; required ater while CS 160, Fall Semester 2014 25 CS 160, Fall Semester 2014 26 Example Mapping between do while and while int count = 1; int sum = 0; do sum += count; count++; while (count <= 5); do while version do statement; while (condition); while version statement; while (condition) statement; How does this differ from the previous? CS 160, Fall Semester 2014 27 CS 160, Fall Semester 2014 28 7

Which loop to use? if ( you know the # of iteraions ) use a for loop else if ( statements should be done at least once ) use a do while loop else use a while loop Problem Solving and FormulaIng Loops Stepwise Development: Break problem into subparts IdenIfy repeaing paaern in problem formulaion Put paaern into body of loop IdenIfy a coninuing condiion (or terminaion condiion) Make separate loops when muliple paaerns are found Make nested loops when one paaern fits within another CS 160, Fall Semester 2014 29 CS 160, Fall Semester 2014 30 Example: Reading Input from User Strategy: Ask user for input Do something with the input Ask user for input Do something with the input UnIl user no longer has input to enter QuesIons: How does user indicate no more input? What is the paaern? What is terminaing condiion? Reading Input Using a Loop Scanner in = new Scanner( System.in ); int score = 0, sumofscores = 0; sentinel do sumofscores += score; System.out.println("Enter score [or -1 for end of input]: "); score = in.nextint( ); while( score!= -1 ); System.out.println("Sum of scores was " + sumofscores); pattern When the user is entering a set of data, you need some way for them to say no more -- called a sentinel. CS 160, Fall Semester 2014 31 CS 160, Fall Semester 2014 32 8

In other words Nested Loops Stepwise refinement don t do everything at once idenify sub- tasks and work on one at the Ime IdenIfy loop paaerns the repeated behavior what is to be done before the loop e.g., iniializaion how is loop terminaion decided what needs to be done ater the loop e.g., store or print results CS 160, Fall Semester 2014 33 Write the code to print out the following: * ** *** **** ***** ****** ******* ******** ********* ********** ALGORITHM OUTER LOOP: 10 times (10 rows) INNER LOOP: 1 to outer loop counter print * go to next line CS 160, Fall Semester 2014 34 Nested Loops CauIons about Loops public class Stars public static void main(string[] args) for( int c = 1; c <= 10; c++ ) for( int i = 0; i < c; i++ ) System.out.print( '*' ); System.out.println( ); Why do we have an empty println? CS 160, Fall Semester 2014 35 Ensure that the required precision of your condiion matches that of the type Recall that two doubles may be mathema5cally equal but not in the computer! Use for muliple statements Check for off- by- 1 errors, most importantly make sure that loop ends at the right Ime) Do NOT put a ; at the end of a for( ) or while( ) statement!!! In a while loop, the condiion must be testable prior to execuing the body In any loop, ensure that the update will eventually cause cause the condiion to become false CS 160, Fall Semester 2014 36 9

CauIons about Loops CauIons about Loops Check for off- by- 1 errors (make sure that it is ending at the right Ime) for ( int i=1; i<100; i++ ) System.out.print( * ); Prints 99 stars. Why? CS 160, Fall Semester 2014 37 Do NOT put a ; at the end of a for( ) or while( )!!! Declares an empty body for the loop. Therefore the statements you think are in the body of the loop actually aren t for ( int i=0; i<100; i++ ); System.out.print( * ); Prints ONE star! Why? CS 160, Fall Semester 2014 38 Infinite Loop Programming PracIce Infinite Loops: loop with a condiional that never becomes false: while( true ) computesquares(); x = 1; while( x < 10 ); x = x + 5; for (int i=1; i>0; i++ ) processoutput( ); y = 1; while( y < 10 ) System.out.print( y ); y++; Run your loops by hand (pencil and paper) Write out expectaions, check them if need be Don t use break and continue in loops They get very confusing very fast Echo values of variables System.out.println( Str: + Str); Use useful idenifiers no one- leaer idenifiers, except for loop indices Declare variables in the right scope OTen at top of scope is good Give yourself a chance to succeed Don t start your project on day before the deadline CS 160, Fall Semester 2014 39 CS 160, Fall Semester 2014 40 10

Loop PracIce Problems Find the minimum integer in a sequence of integers Find the maximum in a sequence of integers Find the longest word in a sequence of words Determine if a word is a palindrome CS 160, Fall Semester 2014 41 11