Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.

Slides:



Advertisements
Similar presentations
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Loops – While, Do, For Repetition Statements Introduction to Arrays
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Copyright 2008 by Pearson Education 1 Midterm announcements Next week on Friday May 8 Must bring an ID Open book, open notes, closed electronics Must attend.
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.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
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.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 102 # T1.
Chapter 5 Loops.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Repetition Statements while and do while loops
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Methods Calling Methods Return.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
COMP Loop Statements Yi Hong May 21, 2015.
CMSC 150 LOOPS CS 150: Fri 20 Jan Representing DNA AGTCCAGTGTCAA.
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
UCT Department of Computer Science Computer Science 1015F Iteration
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Chapter 4 Repetition Statements (loops)
Chapter 5: Control Structures II
Chapter 2.2 Control Structures (Iteration)
Outline Altering flow of control Boolean expressions
Lec 4: while loop and do-while loop
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops COMP 102 #

© Peter Andreae COMP102 11:2 Menu Repetition counted loops loops for input using break Administrivia: Working with other students! You must both declare it labs and help desks next week…..

© Peter Andreae COMP102 11:3 Repetition / Iteration Doing some action repeatedly: “Vacuum the floor until it is clean” “keep watching until midnight” go on handing out tickets as long as there are any people waiting around” “polish each of the cups on the shelf” Common features: An action to repeat Some condition for when to keep going/when to stop

© Peter Andreae COMP102 11:4 Repetion/Iteration in Java LDC 4.5 Several different ways of specifying repetition. One of the simplest is with the while statement: while ( condition ) { actions to perform each time round } while ( true ) { UI.println("this repeats forever!"); } int n = 1; while ( n <= 100) { UI.println(n) ; n = n + 1; } Similar structure to the if statement

© Peter Andreae COMP102 11:5 While syntax Meaning: As long as the condition is still true, repeat the actions one more time Stop once the condition is false. Don’t do it at all if condition is initially false Similar to if, but keeps repeating the actions, as long as the condition is still true each time round no else — just skips to next statement when condition is false while(condition) actions { }

© Peter Andreae COMP102 11:6 While with numbers #1 Print a table of numbers and their squares: public void printTable(int max){ int num = 1; while ( num <= max ) { UI.printf(“ %3d %6d \n”, num, (num*num)); num = num + 1; } } Repetition generally involves initialisation:get ready for the loop test:whether to repeat body:what to repeat “increment”:get ready for the next iteration Initialise Body Test Increment

© Peter Andreae COMP102 11:7 While with numbers #2 Counting down: public void countDown(int start){ int count = start; while ( count >= 1) { UI.println( count ); count = count – 1; } UI.println(“ GO”); } : this.countDown(5); :

© Peter Andreae COMP102 11:8 Nested loops: while inside while public void drawCircles(int rows, int cols) { int row = 0; while (row < rows) { int diam = 20; col = 0; while ( col < cols ) { int x = 50 + row*diam; int y = 20 +col*diam; canvas.fillOval(x, y, diam, diam); col++; } row++; }

© Peter Andreae COMP102 11:9 Reading multiple values from user To ask user for a single value: UI.askString("Enter name: ") UI.askInt("How old are you: ") UI.askDouble("How tall are you: ") To ask for a series of values: UI.print("Enter all the marks: "); double sum = 0; while (….) { sum = sum + UI.nextDouble(); } next(), nextInt(), nextLine(), nextDouble() read and return the next value without further prompting

© Peter Andreae COMP102 11:10 Determining when the user is done Can't just read to the end – the user may still be typing  the program will always wait for input if there is none there Can end at a special value UI.print("Enter all the marks (end with -1): "); double sum = 0; double n = UI.nextDouble( ); while ( n != -1 ) { sum = sum + n; n = UI.nextDouble(); } If reading numbers, can end at a non-number: UI.print("Enter all the marks (end with 'done'): "); double sum = 0; while ( UI.hasNextDouble()) { sum = sum + UI.nextDouble(); } done

© Peter Andreae COMP102 11:11 While with input from user Read numbers from user and count how many 10’s: public void count7s( ){ UI.print(“Enter numbers (‘q’ to quit): ”); int count = 0; while ( UI.hasNextInt( ) ) { int n = UI.nextInt(); if ( n == 10 ) { count = count + 1; } } UI.printf(“There were %d occurrences of 10\n”, count); } What happened to the 'q'? Initialise body test

© Peter Andreae COMP102 11:12 Reading words from user public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); // loop, stopping when you get to 'the' // read next token // increment count UI.printf(“You had %d words before 'the'.", count); }

© Peter Andreae COMP102 11:13 Reading words from user: BAD public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); while ( ! word.equalsIgnoreCase("the”) ) { String word = UI.next(); count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } Too late for the condition!!!

© Peter Andreae COMP102 11:14 Reading words from user: BAD public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); String word = UI.next(); while ( ! word.equalsIgnoreCase("the”) ) { count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } never reads the next word !!!

© Peter Andreae COMP102 11:15 Reading words from user: Fixed public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); String word = UI.next(); while ( ! word.equalsIgnoreCase("the”) ) { count = count + 1; word = UI.next(); } UI.printf(“You had %d words before 'the'.", count); } read next word at end of loop ("increment") read first word before loop

© Peter Andreae COMP102 11:16 Alternate design: using break. public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); while ( true ) { String word = UI.next(); if ( word.equalsIgnoreCase("the”) ){ break; } count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } Note: Textbook does not like this style; I do Only use when the test has to be in the middle of the loop Typically only use with a while (true) {….. The condition is an exit condition, not a keep going condition gets out of the enclosing while loop

© Peter Andreae COMP102 11:17 Designing loops Is the number of steps determined at the beginning? int i = 0;int i = 1; while ( i < number) {while ( i <= number) {  do actions 〉 i = i + 1;i++;} Note, can count from 0 or from 1! Otherwise 〈 intialise 〉 while ( 〈 condition-to-do it again 〉 ) { 〈 body 〉 〈 increment 〉 } Shorthand for i = i+1

© Peter Andreae COMP102 11:18 Designing loops Does exiting the loop depend on the actions? if soor set up for the test while ( true ) { while ( test ) {set up for the test do actionsif ( exit-test ) { set up for the next test break; } do actions } Write out the steps for a couple of iterations including the tests to determine when to quit/keep going Identify the section that is repeated preferably starting with the test Wrap it with a while ( ) { } Identify the condition for repeating.

© Peter Andreae COMP102 11:19 More loops with user input Make user guess a magic word: prompt user for a word test if it is “pumpkin” if not, try again UI.print(“Please enter the magic word:”); String answer = UI.next(); if ( answer.equalsIgnoreCase(“pumpkin”) ) if not, go back where to?? at end UI.println(“You finally guessed it!”);

© Peter Andreae COMP102 11:20 Magic word 1: break to exit Put “while” at the beginning of the repeated section Use the “infinite loop” and an if ( ) { break; } while ( true ) { UI.print(“Please enter the magic word:”); String answer = UI.next(); if ( answer.equalsIgnoreCase(“pumpkin”) ) { break; } UI.println(“You finally guessed it!”);

© Peter Andreae COMP102 11:21 Magic word 2: unfold Put “while” where the test is, Repeat the “set up” in the body. Scanner sc = new Scanner(System.in); UI.print(“Please enter the magic word:”); String answer = sc.next(); while ( ! answer.equalsIgnoreCase(“pumpkin”) ) { UI.print(“Please enter the magic word:”); answer = sc.next(); } UI.println(“You finally guessed it!”);

© Peter Andreae COMP102 11:22 Magic word 3: clever initialisation Set up a “dummy” case first. Scanner sc = new Scanner(System.in); String answer = “ ”; while ( ! answer.equalsIgnoreCase(“pumpkin”) ) { UI.print(“Please enter the magic word:”); answer = scan.next(); } UI.println(“You finally guessed it!”);