Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
CS0004: Introduction to Programming Repetition – Do Loops.
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
LOOP / REPETITION while loop. for loop do/while loop We assume that loops are not meant to be infinite. That is, there should always be a way out of the.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
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
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
©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.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Algorithms Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin,
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.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 6 More Conditionals and Loops
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Java Methods while (chapter < 7) chapter++;
While Statement.
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Unit 3 - The while Loop - Extending the Vic class - Examples
Control Statements Loops.
Control Statements Loops.
Presentation transcript:

Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. while (chapter < 8) chapter++;

8-2 Objectives: Understand the semantics and learn the Java syntax for while, for, and do-while loops Learn how to use nested loops

8-3 Iterations It is essential that a program be able to execute the same set of instructions many times: otherwise a computer would do only as much work as a programmer! Repeating the same code fragment several times is called iterating. Java provides three control statements for iterations (a.k.a. loops): for, while, and do-while.

8-4 The while Loop while ( condition ) { statement1; statement2;... statementN; } while ( condition ) statement1; If the body has only one statement, the braces are optional condition is any logical expression, as in if The body of the loop

8-5 // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p = 1; while ( p < x ) { p * = 2; n++; } return n; } The while Loop (cont’d) Example: Initialization Testing Change

8-6 The while Loop (cont’d) Initialization: The variables tested in the condition must be initialized to some values. If the condition is false at the outset, the loop is never entered. Testing: The condition is tested before each iteration. If false, the program continues with the first statement after the loop. Change: At least one of the variables tested in the condition must change within the body of the loop.

8-7 The while Loop (cont’d) Sometimes change is implicit in the changed state of a variable: Scanner input = new Scanner(inputFile); while (input.hasNext()) System.out.println (input.next()); Changes the state of input

8-8 Loop Invariants A loop invariant is an assertion that is true before the loop and at the end of each iteration. Invariants help us reason about the code. int n = 0, p = 1; while (p < x) { p * = 2; n++; }... Loop invariant: p = 2 n

8-9 The for Loop for is a shorthand that combines in one statement initialization, condition, and change: for ( initialization; condition; change ) { statement1; statement2;... statementN; }

8-10 // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p; for (p = 1; p < x; p * = 2) { n++; } return n; } The for Loop (cont’d) Example: Initialization Testing Change

8-11 The for Loop (cont’d) Java allows you to declare the loop control variable in the for statement itself. For example: for (int i = 0; i < n ; i++) {... } The scope of i is the body of the loop, and i is undefined outside the loop

8-12 The for Loop (cont’d) “Repeat n times” idiom: or for (int i = 0; i < n ; i++) {... } for (int count = 1; count <= n ; count++) {... }

8-13 The for Loop (cont’d) Example: n! = 1 * 2 *... * n /** * Returns 1 * 2 *... * n, if n >= 1 (and 1 otherwise) */ public static long factorial (int n) { long f = 1; for (int k = 2; k <= n; k++) f * = k; return f; }

8-14 The do-while Loop do { statement1; statement2;... statementN; } while ( condition ); The code runs through the body of the loop at least once Always use braces for readability (even if the body has only one statement) if condition is false, the next iteration is not executed

8-15 The do-while Loop (cont’d) do-while is convenient when the variables tested in the condition are calculated or read in the body of the loop: String str; do { str = file.readLine();... } while (str != null);

8-16 The do-while Loop (cont’d) do-while can be easily avoided: we can usually replace it with a while loop initialized so that it goes through the first iteration: String str = "dummy"; while (str != null) { str = file.readLine();... }

8-17 break and return in Loops break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop. return in a loop instructs the program to immediately quit the current method and return to the calling method. A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable.

8-18 break in Loops Example: int d = n - 1; while (d > 0) { if (n % d == 0) break; d -- ; } if ( d > 0 ) // if found a divisor...

8-19 return in Loops Sequential Search method: public int search(String[ ] list, String word) { for (int k = 0; k < list.length; k++) { if (list[k].equals (word) return k; } return - 1; }

8-20 Nested Loops A loop within a loop is called nested. // Draw a 5 by 3 grid: for (int x = 0; x < 50; x += 10) { for (int y = 0; y < 30; y += 10) { g.fillRect(x, y, 8, 8); }

8-21 Nested Loops (cont’d) Braces are optional when the body of the loop(s) is one statement: for (int x = 0; x < 100; x += 10) for (int y = 0; y < 200; y += 10) g.fillRect(x, y, 8, 8); Inner for is the only statement in the outer for’s body Many programmers prefer to always use braces in loops, especially in nested loops.

8-22 Nested Loops (cont’d) Be careful with break: int r, c; for (r = 0; r < m.length; r++) { for (c = 0; c < m[0].length; c++) { if (m [ r ][ c ] == 'X' ) break; }... Breaks out of the inner loop but continues with the outer loop

8-23 “Triangular” Nested Loops “Find duplicates” idiom: for (int i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a [ i ].equals(a [ j ]) System.out.println ("Duplicate " + a [ j ] ); } The inner lcv starts at the outer lcv’s next value

8-24 Lab: Perfect Numbers A perfect number is a positive integer equal to the sum of all its divisors (including 1 but excluding the number itself). For example: 28 = Write a program to find the first four perfect numbers (Java Methods A & AB pp ).

8-25 Lab: Perfect Numbers (cont’d) Euclid showed that if 2 n - 1 is a prime, then 2 n - 1 (2 n - 1) is a perfect number. For example: = 7 is a prime => 2 2 ( ) = 28 is a perfect number Euclid Around 300 BC

8-26 Lab: Perfect Numbers (cont’d) A prime that has a form 2 n - 1 is called a Mersenne prime. Marin Mersenne Leonhard Euler Write a program to find the first six Mersenne primes and the corresponding perfect numbers. Euler proved that any even perfect number must have that form.

8-27 Lab: Perfect Numbers (cont’d) The 44th Mersenne Prime, 2 32,582, = (9,808,358 digits), was discovered in September There is a $100,000 reward for finding a 10 million digit prime number.

8-28 Review: Name three iterative control statements in Java. What is the difference between while and do-while? Can any code with a for loop be rewritten with a while loop? Does short-circuit evaluation apply to conditions in loops? Which operators can be used in the “change” part of a for loop?

8-29 Review (cont’d): Are method calls allowed in a condition in a while loop? Is return allowed in a loop? What is a nested loop? Name a situation where nested loops are used. Can you have nested while loops?