©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Repetition Chapter 4: Control structures. Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2 Loop Statements After reading and studying this Section,
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 6 Repetition Statements Animated Version.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Confirmation Dialog Formatting Output.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
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.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to Implement repetition control.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Chapter 6 Repetition Statements. Objectives Understand repetition control (loop ) statements in Java: while statement. do-while statement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition Statements.
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.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 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 STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
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.
Fundamentals of Python: From First Programs Through Data Structures
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 5 Loops.
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.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
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.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
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.
A First Book of C++ Chapter 5 Repetition.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CS-1010 Dr. Mark L. Hornick 1 Selection and Iteration and conditional expressions.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
While ( number
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
REPETITION CONTROL STRUCTURE
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Chap 7. Advanced Control Statements in Java
Looping and Repetition
Presentation transcript:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement assignment operators  Repetition while do-while for

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  Updating a variable by adding or subtracting 1 is a very common operation i = i + 1; j = j - 1;  Java has operators that allow you to write this more compactly i++ and ++i for incrementing j-- and --j for decrementing  Both operators can come either before (prefix) or after (postfix) the operand.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  In a statement by themselves, the prefix and postfix operators do the same thing.  The variable being incremented gets updated at different times if these operators are embedded in a bigger expression prefix : increment/decrement performed first postfix : increment/decrement done last

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  If count currently contains 45, then the statement total = count++; assigns 45 to total and 46 to count  If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  Another common operation consists of performing an operation on that variable and storing the result back in the same variable  Java provides assignment operators to simplify this process  For example, the statement num = num + count; can be replaced by num += count;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  Java also provides assignment operators for all the binary operations. x += a;add a to x and store the new value x -= a;subtract a from x and store the new value x *= a;multiply x by a and store the new value x /= a;divide x by a and store the new value i %= j;replace i by i % j

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  The right hand side of an assignment operator can be a complex expression  Semantics of assignment operators: The entire right-hand expression is evaluated Then the result is combined with the original variable  For example result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  The behavior of some assignment operators depends on the types of the operands  If the operands to the += operator are strings, the assignment operator performs string concatenation  The behavior of an assignment operator ( += ) is always consistent with the behavior of the "regular" operator ( + )  The /= operator does integer or floating point division depending on its operands.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Repetition  Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met.  Java has three repetition statements: while do-while for

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The while Statement  In Java, while statements follow a general format: while ( )  For example: int sum = 0, number = 1; while (number <= 100){ sum = sum + number; number = number + 1; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The while Statement  Repetition statements are also called loop statements, and the is known as the loop body.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Semantics of a while Statement  The is evaluated.  If the is true, the is executed.  This sequence is repeated as long as the is true.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow chart for while

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Loop Patterns  In a count-controlled loop, the loop body is executed a fixed number of times. int counter = 0; while (counter < 100) doSomething();  In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered. int value = kbd.nextInt(); while (value != SENTINEL) value = kbd.nextInt();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Repetition Pitfalls  There are several different types of potential programming problems we should keep in mind as we develop our programs. When writing repetition statements, it is important to ensure that the loop will eventually terminate. It is important that the boolean expression be correct.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Infinite loops * An infinite loop will never stop int product = 0; while (product < 5000) { product = product * 5; }  Because product is initialized to 0, product will never be larger than 5000 (0 = 0 * 5), so the loop will never terminate.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Another Infinite Loop  In this example, (the while statement of which is also an infinite loop), count will equal 9 and 11, but not 10. int count = 1; while (count != 10) { count = count + 2; }  This is a case of not thinking about the termination condition carefully enough.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. More Pitfalls  The off-by-one error is another frequently-encountered pitfall. Check the initial value of your loop variable carefully Check the condition you use for terminating the loop

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Use real numbers properly  Real numbers should not be used in testing or increment, because only an approximation of real numbers can be stored in a computer. double x = 0.0; while (x<=1.0) x = x +.1;  Real numbers should not be tested for equality Math.abs(x - 1.0) <.01

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The do-while Statement  The while statement is a pretest loop, because the test is done before the execution of the loop body. Therefore, the loop body may not be executed.  The do-while statement is a posttest loop. With a posttest loop statement, the loop body is executed at least once.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Syntax of do-while  The format of the do-while statement is: do while ( );  The is executed until the becomes false.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example of do-while Statement int sum = 0, number = 1; do { sum += number; number++; } while (sum <= );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for do-while

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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. Example: when reading data until some sentinel value is entered, you don't generally want to process the sentinel.  It is implemented by using reserved words while, if, and break.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Loop-and-a-Half Example String name; while (true){ name = JOptionPane.showInputDialog(null, "Your name"); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, "Invalid Entry. " + "You must enter at least one character."); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Alternate Loop-and-a-Half for Input String name = kbd.next(); while (name.length() == 0){ System.out.println("Invalid Entry. " + "You must enter at least one character."); name = kbd.next(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for loop-and-a-half

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pitfalls  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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Confirmation Dialog  JOptionPane has another form of dialog that we haven't seen before  A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, "Play Another Game?", /*prompt*/ "Confirmation", /*dialog title*/ JOptionPane.YES_NO_OPTION /*button options*/);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The for Statement  The for statement is good for counting loops.  The syntax of the for statement is as follows: for ( ; ; ) int i, sum = 0; for (i = 1,i <=100, i++){ sum += i; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for for Statement

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The for Statement  The variable i in the example statement is called a control variable. It keeps track of the number of repetitions.  The can be by any amount, positive or negative.  for statements are often used for counting loops.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Ch6DroppingWaterMelon.java  We want to to calculate the position of an object dropped from height H at t=0 as a function of time P = H - 16 t 2  Use a loop and test for H<=0

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Nested loops  A loop statement can be nested inside another loop statement.  The inner loop repeats the appropriate number of times for each execution of the outer loop.  For example, in for (int i=0; i<10; i++) for (int j=0; j<5; j++) sum += i + j; the body of the loop executes 10 * 5 = 50 times.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example:  The price table for carpets ranging in size from 11 x 5 to 20 x 25 ft. whose unit price is $19 per sq. ft.  The outer for statement ranges from the first row (width = 11) to the last row (width = 20).  For each repetition of the outer for, the inner for statement is executed, which ranges from the first column (length = 5) to the fifth (length = 25).

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Nested loops  A loop statement can be nested inside another loop statement. int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19/sq. ft. System.out.print (" " + price); } //finished one row; move on to next row System.out.println(""); }