©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 1 Repetition Statements.

Slides:



Advertisements
Similar presentations
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Advertisements

CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repetition Chapter 4: Control structures. Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2 Loop Statements After reading and studying this Section,
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
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.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Odds and Ends  Formatted Output  Random numbers.
©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.
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 – 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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
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.
©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.
©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.
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.
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
Loops and Iteration for Statements, while Statements and do-while Statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
While ( number
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Repetition Statements
Chapter 4 Repetition Statements (loops)
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Intro to OOP with Java, C. Thomas Wu
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 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Iteration: Beyond the Basic PERFORM
Building Java Programs
Loops and Iteration CS 21a: Introduction to Computing I
Chapter 7 Repetition Statements
Looping and Repetition
Presentation transcript:

©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 Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered. Repetition statements are called loop statements also.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter while ( number <= 100 ) { sum = sum + number; number = number + 1; } Syntax for the while Statement while ( ) Statement (loop body) Boolean Expression

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Control Flow of while int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; sum = sum + number; number = number + 1; true

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter More Examples Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. Computes the product of the first 20 odd integers. int sum = 0, number = 1; while ( sum <= ) { sum = sum + number; number = number + 1; } 1 1 int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while (number <= lastNumber) { product = product * number; number = number + 2; } 2 2

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Finding GCD

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter String inputStr; int age; System.out.println( "Your Age (between 0 and 130):"); age = scanner.nextInt(); while (age 130) { System.out.println( "An invalid age was entered. Please try again."); System.out.println( "Your Age (between 0 and 130):"); age = scanner.nextInt(); } Example: Testing Input Data Priming Read

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to OperatorUsageMeaning +=a += b;a = a + b; -=a -= b;a = a – b; *=a *= b;a = a * b; /=a /= b;a = a / b; %=a %= b;a = a % b;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Watch Out for Pitfalls 1.Watch out for the off-by-one error (OBOE). 2.Make sure the loop body contains a statement that will eventually cause the loop to terminate. 3.Make sure the loop repeats exactly the correct number of times. 4.If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N.

Loop Pitfall - 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 2 int product = 0; while ( product < ) { product = product * 5; } 1 1

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Overflow An infinite loop often results in an overflow error. An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Loop Pitfall - 2 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count != 1.0f ) { count = count f; } //eight 3s 2 2 float count = 0.0f; while ( count != 1.0f ) { count = count f; }//seven 3s 1 1

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Loop Pitfall – 2a int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result); 1 1 int result = 0; double cnt = 0.0; while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result); 2 2 Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while ( count < 10 ){... count++; } 1 1 count = 0; while ( count <= 10 ){... count++; } 3 3 count = 1; while ( count <= 10 ){... count++; } 2 2 count = 0; while ( count < 10 ){... count++; } andexhibit off-by-one error.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The for Statement int i, sum = 0, number; for (i = 0; i < 20; i++) { number = scanner.nextInt( ); sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, …, 19).

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } Syntax for the for Statement for ( ; ; ) Initialization Boolean Expression Increment Statement (loop body)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Control Flow of for i = 0; false number =... ; sum += number; true i ++; i < 20 ?

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The Nested-for Statement Nesting a for statement inside another for statement is commonly used technique in programming. Let’s generate the following table using nested-for statement.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Generating the Table int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19 per sq. ft. System.out.print (“ “ + price); } //finished one row; move on to next row System.out.println(“”); } INNER OUTER

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6. From Java 5.0, we can use the Formatter class. System.out (PrintStream) also includes the format method.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The Formatter Class We use the Formatter class to format the output. First we create an instance of the class Formatter formatter = new Formatter(System.out); Then we call its format method int num = 467; formatter.format("%6d", num); This will output the value with the field width of 6.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The format Method of Formatter The general syntax is format(,,,... ) Example: int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format("%6d", 498); is equivalent to System.out.format( "%6d", 498 );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Control Strings Integers % d Real Numbers %. f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class.