Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.

Slides:



Advertisements
Similar presentations
Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested.
Advertisements

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.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 6 Repetition Statements Animated Version.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Loops and Files.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Chapter Chapter 6 Repetition Statements. Objectives Understand repetition control (loop ) statements in Java: while statement. do-while statement.
Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©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
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.
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Chapter 5 Loops.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
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.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
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.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Lecture 4b Repeating With Loops
Chapter 5: Control Structures II
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Control Statements Loops.
Repetition Control Structure
Alternate Version of STARTING OUT WITH C++ 4th Edition
Control Statements Loops.
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.
Presentation transcript:

Loop variations do-while and for loops

Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop body is performed first, then condition is tested A do-while loop is guaranteed to perform one iteration, because the validity of the condition is not known until after the iteration is complete

Syntax for do-while loop do { /* loop body statements */ }while (expression); Notes: do-while loops are almost always event-controlled Often not necessary to initialize loop control Good idea to keep end bracket and while(expression) on same line

do { sum += number; number++; } while ( sum <= ); Syntax for the do-while Statement do while ( ) ; Statement (loop body) Boolean Expression

Control Flow of do-while int sum = 0, number = 1 sum += number; number++; sum += number; number++; sum <= ? true false

Applications for do-while loops Often used to display an initial menu of choices, one of which is “quit program” – you want user to see this at least once, even if the option they pick is to quit Useful for checking validity of input value – eliminates having to prompt twice for same data (see examples, next two slides)

Validating input – while loop Scanner kb = new Scanner(System.in); int x; System.out.print(“Enter a number between 1 and 100: ”); x = kb.nextInt(); while(x 100) { System.out.println(“Value out of range”); System.out.print(“Enter a number between 1 and 100: ”); x = kb.nextInt(); }

Validating input – do-while loop Scanner kb = new Scanner(System.in); int x; do { System.out.print(“Enter a number between 1 and 100: ”); x = kb.nextInt(); if (x 100) System.out.println(“Value out of range”); } while(x 100);

Do-While Loop vs. While Loop POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all.

Confirmation Dialog A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, /*prompt*/ "Play Another Game?", /*dialog title*/ "Confirmation", /*button options*/ JOptionPane.YES_NO_OPTION);

Example: Confirmation Dialog boolean keepPlaying = true; int selection; while (keepPlaying) { //code to play one game comes here //... selection = JOptionPane.showConfirmDialog(null, "Play Another Game?", "Confirmation", JOptionPane.YES_NO_OPTION); keepPlaying = (selection == JOptionPane.YES_OPTION); }

Example: Confirmation Dialog int selection; do { //code to play one game comes here //... selection = JOptionPane.showConfirmDialog(null, "Play Another Game?", "Confirmation", JOptionPane.YES_NO_OPTION); } while ( selection == JOptionPane.YES_OPTION);

For loops Count-controlled loops are so common in programming that most languages have a special set of syntax designed specifically for this construct for loopIn Java, the special syntax for a count- controlled loop is called a for loop

Count-controlled loops Count-controlled while loop: –initialize counter before loop starts –test counter in loop control expression –update counter inside loop body A for loop is a stylized version of a count- controlled while loop; all of the elements above appear at the top of the loop

For Loop Syntax for ( initialization ; test expression ; update ) { 0 or more statements to repeat }

Control Flow of for i = 0; false number =... ; sum += number; true i ++; i < 20 ?

The for loop contains an initialization an expression to test for continuing an update to execute after each iteration of the body

Count-controlled while loop example int x=0;/* step 1: initialize counter */ while (x < 100) /* step 2: test counter value */ { System.out.println(“I will be a good student”); x++;/* step 3: increment counter */ }

Same logic using for loop for (int x=0; x<100; x++) System.out.println(“I will be a good student”); Step 1: initialize loop counter (performed once) Step 2: test counter value (performed once for each iteration) Step 3: increment loop counter (performed once per iteration) Body of loop is performed between steps 2 and 3, just as in the while loop version

Notes on for loop Just stylized version of while loop; condition test occurs before each iteration Can contain single statement (making brackets unnecessary) because increment occurs in loop heading Each section of loop heading can contain multiple parts, separated by commas; each section can also be omitted

for (int count = 4 ; count > 0 ; count -- ) { System.out.println(“” + count); } System.out.println(“Done”); Example using decrement OUTPUT: Done

Write a loop to produce the following output: 1Potato 2Potato 3Potato 4 5Potato 6Potato 7Potato More

What is output? int count=0; for (; count < 10 ; count++ ) { System.out.println(“  ”); }

What is output? int count=0; for (; count < 10 ; count++ ); { System.out.println(“*”); }

More for Loop Examples for (int i = 0; i < 100; i += 5) 1 1 i = 0, 5, 10, …, 95 for (int j = 2; j < 40; j *= 2) 2 2 j = 2, 4, 8, 16, 32 for (int k = 100; k > 0; k--) ) 3 3 k = 100, 99, 98, 97,..., 1

Example – multiplication table The loop displays a specified multiplication table. For example, if the user enters 6, the program displays this table: 1 x 6 = 6 2 x 6 = 12 3 x 6 = x 6 = 72

import java.util.*; public class Mtable { public static void main(String [] args) { int value; Scanner kb = new Scanner(System.in); System.out.print (“Enter value for table: ”); value = kb.nextInt(); for (int ct = 1; ct <= 12; ct++) System.out.println( “” + ct + “ x ” + value + “ = ” + ct * value); }

Loop-and-a-Half Repetition Control Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body. It is implemented by using reserved words while, if, and break.

Example: Loop-and-a-Half Control String name; while (true) { name = JOptionPane.showInputDialog(null, "Your name"); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, "Invalid Entry.\n" + "You must enter at least one character."); }

Pitfalls for Loop-and-a-Half Control Be aware of two concerns when using the loop-and-a-half control: –The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop. –Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow.