Loop Structures.

Slides:



Advertisements
Similar presentations
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Advertisements

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
Chapter Day 14. © 2007 Pearson Addison-Wesley. All rights reserved5-2 Agenda Day 14 Problem set 3 posted  10 problems from chapters 5 & 6  Due in 11.
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.
Chapter Day 12. © 2007 Pearson Addison-Wesley. All rights reserved5-2 Agenda Day 12 Problem set corrected  1 A, 2 B’s and 1 D Starting Late and not turning.
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.
© 2007 Lawrenceville Press Slide 1 Chapter 6 The while Statement  Loop structure that executes a set of statements as long as a condition is true  The.
Java Programming: From the Ground Up
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Chapter 5 Loops.
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.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Repetition Statements while and do while loops
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Outline The if Statement and Conditions Other Conditional.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
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.
Repetition Statements b Repetition statements allow us to execute a statement multiple times repetitively b They are often simply referred to as loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Unit 3 Lesson 9 Repetition Statements (Loops)
Chapter 5: Control Structures II
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
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.
Chapter 6 The while Statement
Chapter 6 More Conditionals and Loops
Debugging October 3, 2007 ComS 207: Programming I (in Java)
Outline Altering flow of control Boolean expressions
Chapter 4: Loops and Files
The ‘while’ Statement September 27, 2006
3.5- The while Statement The while statement has the following syntax:
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
CprE 185: Intro to Problem Solving (using C)
Debugging October 4, 2006 ComS 207: Programming I (in Java)
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
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.
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
CprE 185: Intro to Problem Solving (using C)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

Loop Structures

Goals and Objectives while loop do-while loop for loop Infinite Loops Nested Loops Counter Accumulator Sentential Value for each loop

Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation

4 Types of loops while (boolean condition) do – while (boolean condition) for(initialization;condition;update) For each loop (Discussed later)

while Loop Executes a set of statements over and over again based on a condition. Pretest Loop Variable Loop Iteration – each execution of the loop. Example: while(condition) { <statements>; }

7/28/2018 8:39 PM The while Statement Loop structure that executes a set of statements as long as a condition is true The condition is a Boolean expression Will never execute if the condition is initially false The loop below iterates once because the condition is true and then continues to iterate until response is not 1: response = 1; while (response == 1) { System.out.print("Enter 1 or 0:"); response = input.nextInt(); } Refer to page 131 in the text.

3 parts of a while loop Initialization – (Priming the loop) Terminating condition Updating statement Example: x = 0; // initialization while(x < 10) // x < 10 is the termination condition { x++; // increase x by 1 updating statement }

Logic of a while Loop condition evaluated false statement true

The while Statement An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

The while Statement A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input A loop can also be used for input validation, making a program more robust

Trace a while loop final int LIMIT = 5; int count = 1; while(count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“Done”); Output: 1 2 3 4 5 Done

do – while loop Alternative form of the while loop statement. Not evaluated until after the first execution of the loop. Guarantee to execute once not like the other two loops. Post-test loop Variable loop Example: do { <statements>; } while(condition);

3 parts of a do while loop Initialization – (Priming the loop) Terminating condition Updating statement Example: x = 0; // initialization do { x++; // increase x by 1 updating statement } while(x < 10); // x < 10 is the termination condition

The do-while Statement 7/28/2018 8:39 PM The do-while Statement Alternative form of the while statement Executes at least once The statement do { System.out.print("Enter 1 or 0:"); response = input.nextInt(); } while (response == 1); iterates once and continues to iterate until response is not 1. Refer to pages 131 and 132 in the text.

The do Statement A do statement has the following syntax: do { } while ( condition ); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

Logic of a do Loop statement true condition evaluated false

The do Statement An example of a do loop: int count = 0; do { count++; System.out.println (count); } while (count < 5); The body of a do loop executes at least once

Comparing while and do The while Loop The do Loop statement condition true false condition evaluated The while Loop true condition evaluated statement false The do Loop

Example of a do – while loop int count = 1; int limit = 5; do { System.out.println(count); count++; }while(count<limit); System.out.println(“Done”) Output: 1 2 3 4 Done

for loop A counter controlled repetition loop, works well when you know exactly how many times you want to execute the loop. Fixed Loop Pre-Test Loop

3 parts of a for loop Initialization Boolean condition Update Example: for(initialization; boolean condition; update) { <statements>; }

7/28/2018 8:39 PM The for Statement Loop structure that executes a set of statements a fixed number of times Uses a loop control variable (lcv) The increment (++) or decrement (--) operators are used to change the value of the loop control variable The loop below executes until i is greater than 10: for (int i = 0; i <= 10; i++) { sum += i; } Refer to page 135 in the text.

The for Statement A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

Logic of a for loop initialization condition evaluated false statement true increment

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }

The for Statement An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

The for Statement The increment section can perform any calculation for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed

Example of a for loop int limit = 5; for(int count = 1; count <limit; count++) { System.out.println(count); } System.out.println(“Done”);

Missing sections of a for loop You can have sections of a for loop missing just as long as you have that section declared and initialized somewhere else. Semicolon still must appear between sections Example: for( ; x<5; x++) Or for( ; x < 5; )

Trace a for loop final int LIMIT = 5; for(int count = 1; count<= LIMIT; count++) System.out.println(count); System.out.println(“Done”); OUTPUT: 1 2 3 4 5 Done Notice the for loop has no braces. Just like the if statement, it will only repeat the first statement only

Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely

Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) System.out.println ("Here"); count2++; } count1++; 10 * 20 = 200

Nested Loops Loop that contains another loop in its body. Example: for(int x = 0; x< 5; x++) { System.out.println(“Outer Loop”); for(int y = 0; y < 5; y++) System.out.println(“Inner Loop”); } It is very important to indent the inner loop Make sure you reset inner loop to reenter again.

Infinite Loops A loop that continues executing forever 7/28/2018 8:39 PM Infinite Loops A loop that continues executing forever Can be caused by syntax or logic errors. For example: while (num < 0) //error--no braces System.out.print("Enter a vale: "); num = input.nextInt(); Some errors can result in an overflow Refer to page 132 in the text. An infinite loop can cause an application to stop responding or just "hang". Closing the application window (with JCreator Pro) will end the application so that the source of the infinite loop can be located and corrected. Errors that result in an overflow may generate unexpected results rather than "hanging" the application.

Infinite Loops Loops where the boolean condition never becomes false. Example int x = 0; while(x < = 5) { System.out.println(“Hello”); } x is never updated to become bigger than 5

Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

Infinite Loops An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } This loop will continue executing until interrupted (Control-C) or until an underflow error occurs

Accumulators, Counters, & Sentinel Values Accumulator is a variable in a loop that keeps a running total or sum of a variable. Counter – is usually a variable increase by one to keep a record of how many times a loop has executed. Sentinel Value (Flag) – are inputted by the user to stop a loop. –999 or –1 Be careful not to add the sentinel value to the accumulator.

A variable that is incremented by a constant value 7/28/2018 8:39 PM Counters A variable that is incremented by a constant value Often used for counting loop iterations Should be initialized to 0 when declared The counter in the loop counts the number of responses: do { System.out.print("Enter 1 or 0:"); response = input.nextInt(); numResponses += 1; } while (response == 1); Refer to page 133 in the text.

Accumulators A variable that is incremented by a varying amount 7/28/2018 8:39 PM Accumulators A variable that is incremented by a varying amount Often used for summing Should be initialized to 0 when declared The accumulator in the loop sums values: do { System.out.print("Enter grade:"); grade = input.nextInt(); sumOfGrades += grade; } while (grade != 999); Refer to page 133 in the text.

7/28/2018 8:39 PM Using Flags A flag, or sentinel, indicates when a loop should stop iterating Often a constant Code is easier to modify when sentinels are constants declared at the beginning of an application A flag is used in the condition of the loop: final int STOP = 999; do { System.out.print("Enter grade:"); grade = input.nextInt(); sumOfGrades += grade; } while (grade != STOP); Refer to page 133 in the text.

Breaking out of a loop An if statement with the keyword break as a statement. When the if statement becomes true it will execute the break statement and take you out of that loop. If you have multiple nested loops the break will only break you out of the loop that it is located in.

Debugging Techniques The debugger included with many compilers 7/28/2018 8:39 PM Debugging Techniques The debugger included with many compilers Variable trace, which is a manual technique of list values of variables at the points of assignment Additional println() statements for displaying variable values at points of assignment "Commenting out" code to detect bugs through a process of elimination Refer to pages 136 and 137 in the text.

Using println() to Debug 7/28/2018 8:39 PM Using println() to Debug int num1 = 0; int num2 = 0; System.out.println("num1 before while: " + num1); //debug while (num1 < 10) { System.out.println("num1 in while: " + num1); //debug if (num1 % 3 == 0) { num2 += num1; System.out.println("num2: " + num2); //debug System.out.print(num2 + " "); } num1 += 1; } Refer to page 137 in the text. When using println() statements to debug a segment of code, it is usually most effective to place statements just after assignment changes the value of a variable.

Using Comments to Debug 7/28/2018 8:39 PM Using Comments to Debug int num1 = 0; int num2 = 0; while (num1 < 10) { //if (num1 % 3 == 0) { // num2 += num1; // System.out.print(num2 + " "); //} num1 += 1; } Refer to page 137 in the text. Comments can be used to comment out segments of code to determine through a process of elimination the location of any bugs.

7/28/2018 8:39 PM Variable Trace int num1 = 0; int num2 = 0; while (num1 < 10) { if (num1 % 3 == 0) { num2 += num1; System.out.print(num2 + " "); } num1 += 1; } Refer to page 136 in the text.

Iterators An iterator is an object that allows you to process a collection of items one at a time It lets you step through each item in turn and process it as needed An iterator object has a hasNext method that returns true if there is at least one more item to process The next method returns the next item Iterator objects are defined using the Iterator interface.

Iterators Several classes in the Java standard class library are iterators The Scanner class is an iterator the hasNext method returns true if there is more data to be scanned the next method returns the next scanned token as a string The Scanner class also has variations on the hasNext method for specific data types (such as hasNextInt)

Iterators The fact that a Scanner is an iterator is particularly helpful when reading input from a file Suppose we wanted to read and process a list of URLs stored in a file One scanner can be set up to read each line of the input until the end of the file is encountered Another scanner can be set up for each URL to process each part of the path

Iterators and for Loops Recall that an iterator is an object that allows you to process each item in a collection A variant of the for loop simplifies the repetitive processing the items For example, if BookList is an iterator that manages Book objects, the following loop will print each book: for (Book myBook : BookList) System.out.println (myBook);

Iterators and for Loops This style of for loop can be read "for each Book in BookList, …" Therefore the iterator version of the for loop is sometimes referred to as the for each loop It eliminates the need to call the hasNext and next methods explicitly It also will be helpful when processing arrays.

Common Errors Boolean condition never becoming false causing an infinite loop. Semicolon after a for or while loop Adding a sentinel value to an accumulator Missing semicolon after the while in a do – while loop. Forgetting to reset the inner loop to go back in.