 Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0.

Slides:



Advertisements
Similar presentations
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
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.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
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.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Primitive Types CSE 115 Spring 2006 April 3 &
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
5.05 Apply Looping Structures
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.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
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 (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Definite Loops Instructor Rob Nash. What is Definite Looping? A loop: a block of code that is repeated a number of times A definite loop: a block of code.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter Looping 5. The Increment and Decrement Operators 5.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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Chapter 4 – C Program Control
Loop Structures.
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements I
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
3 Control Statements:.
Chapter 6 Control Statements: Part 2
M150: Data, Computing and Information
Chapter 2 Programming Basics.
Chapter 4 - Program Control
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:

 Instructor Nash  Readings: Savitch, Chapter 3 (Section 3)  CSS 161 V2.0

 Have: ◦ A loop variable (integer) ◦ A starting or initial value ◦ A final or terminal value ◦ An increment or decrement  And conceptually: ◦ Should do some work each iteration  I.e., progress the state of the loop  Should be moving from start to finish

? Code Block True False

? Code Block True False

  while( ) { ◦ ◦ … ◦  }

 For( expression1; expression2; expression3) { ◦ //body  }  Exp1: Loop variable declaration and initial value  Exp2: Loop continuation test and terminal value  Exp3: Increment or decrement ◦ Should move from initial to terminal value, else infinite!

 Exp1: Loop variable declaration and starting value  Exp2: Loop continuation test and terminal value  Exp3: increment or decrement   while( ) { ◦ //body ◦  }  for( ; ; ){ ◦ //body  }

 Similar to a “For”, but less centralized  Most “For” loops can be rewritten as a “While” and vice versa  The “For” header combines: ◦ Loop variable declaration and initialization ◦ A loop test  Thus a terminal value ◦ An increment that brings the loop variable closer to the terminal value  Note that, just like a For, if the test is initially false, we skip the whole loop!

 A While loop continues to execute while the condition remains true  For example, we might look while x < 6  To build such a “loop test” or “question”… ◦ We’re really building a boolean expression ◦ This will evaluate to {true, false} ◦ To do so, use a relational operator:  {, ==, !=, =}

 {, ==, !=, =}  Used to relate two quantities or objects  Posit questions such as: ◦ Is x less than y? ◦ Are a and b equal? ◦ Are y and z not equal? ◦ Is GPA greater than a 3.0?  Note: we may need to combine two simple boolean expressions

 Frequently, we’ll need to group together multiple simple expressions into a compound expression:  if( digit >= 0 && digit <= 9 )  if( digit > 0 && digit % 2 == 0)  We can create these using Logical Operators  {AND, OR, NOT} //in java, {&&, ||, !} letterGrade >= ‘a’ & letterGrade <=‘f’ & letterGrade != ‘e’)

 Used to make compound boolean expressions ◦ Loop tests and If tests  && is AND ◦ conjunction  || is OR ◦ disjunction  ! is NOT ◦ negation  //note: above implies short-circuit evaluation  //below implies no short-circuit evaluation  & is AND  | is OR

 pqp && q  TrueTrueTrue  FalseTrueFalse  TrueFalseFalse  FalseFalseFalse  //note that False AND X is always False ◦ Useful for short circuit evaluation later

 pqp || q  TrueTrueTrue  FalseTrueTrue  TrueFalseTrue  FalseFalseFalse  //Note that True OR X is always True ◦ Useful for short-circuit evaluation

 p!p  True False  FalseTrue

 Consider the code to stop at the first space: ◦ int stop = 0; ◦ while(s.charAt(stop) != ‘ ‘ && stop < s.length() ) {  stop++; ◦ }  When the above code gets to the last letter in the string “foo”, what will happen? ◦ stop will be incremented, and the next call to charAt will throw an exception

 Defn: If we know the boolean result from our first computation, don’t do any more computations. ◦ TRUE OR X -> TRUE ◦ FALSE AND Y -> FALSE  Previous example, consider swapping the order and relying on short-circuiting:

◦ int stop = 0; ◦ while(stop < s.length() && s.charAt(stop) != ‘ ‘ ) {  stop++; ◦ }  Now, if we ever go over the length of the string, the first part of the compound expression above will evaluate to false, and we won’t execute the charAt!

 The number of times to loop is known in advance  These are “static” loops – happens the same amount each time, every time.  for(int r = 0; r < 10; r++)  int number = 0; //problem here?  while( number <= 512 ) { ◦ number *= 2;  }

 We can’t tell just by observing the code how many times these loops will iterate ◦ These loops may change their behaviour based on:  User input  Date and time  A (pseudo)random number  while( isLoggedIn == false) { ◦ isLoggedIn = QueryUsernamePassword();  }  int someRandInt = (int) Math.rand() * 100  for( int r = 0; r < someRandInt; r++) {…}

 Sometimes, we ask the user to control our loops  For example, consider a grade averaging algorithm ◦ We could ask ahead of time “how many grades?” ◦ Or, we could use a dummy or Sentinel value  These must be chosen with care so as to not confuse with valid user input – in this example, a quiz score.  “-1” is a good dummy value here, since its not a legal score

 Defn: A sentinel is a unique value that signals the end of input. ◦ To be a sentinel value, you must be distinguishable from “normal” or expected input ◦ Also, you shouldn’t factor in the sentinel to your calculations (see below)  Classic “loop-and-a-half” problem  nextGrade = getGradeFromUser();  while( nextGrade != -1 ) { ◦ sum += nextGrade; ◦ nextGrade = getGradeFromUser();  }

 Some OSes use a specific value to indicate end-of-file ◦ Called an EOF sentinel  while( ! currentFile.isEOF() ) { ◦ readNextLine();  }

 int smallestDivisor = 2; //why 2?  while( number % smallestDivisor != 0) ◦ smallestDivisor++;

 while( someNumber < 100 ) { ◦ //body ◦ //needs a statement like “someNumber = …;“  }  If someNumber starts less than 100, and  The body never updates or changes this variable  We will loop forever! ◦ Key idea: if your loop test hinges on a variable, you must update that variable inside the loop body  If the loop variable never changes and the condition is initially true, it will always be true – stuck in stasis!

 Ignore the concept of “Forever” looping ◦ Says “optional” in the text  Also, be wary of “breaking” too much  Read page 301 for history, but I wonder about some of the research and how it’s evaluated ◦ Djikstra is awesome

 You can “break;” out of a loop ◦ Similar to “return” for functions  You can break out of loops nested in other loops ◦ Usually, use this only for performance  ForEach( element of 100,000,000 ) { ◦ If( foundIt ) {  index = currentIndex;  break; //don’t inspect the rest! ◦ }  }