Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition 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.
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.
©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.
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.
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.
© 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 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.
Fundamentals of Python: From First Programs Through Data Structures
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
CS1101X: Programming Methodology Recitation 3 Control Structures.
Chapter 5 Loops.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Discussion 4. Labs public MyPoint(double xInit, double yInit ) { MyPoint p = new MyPoint(0, 0); } ClassProblem.java recursive java.lang.StackOverflowError.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Chapter 4: Control Structures II
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 5 Repetition.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
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.
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
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Repetition Statements
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Intro to OOP with Java, C. Thomas Wu
Repetition-Sentinel,Flag Loop/Do_While
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.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Repetition Statements
Chapter 7 Repetition Statements
Looping and Repetition
Presentation transcript:

Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program using while statements. Implement repetition control in a program using do-while statements. Implement repetition control in a program using for statements. Prompt the user for a yes-no reply using the showConfirmDialog method of JOptionPane.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Definition 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 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 String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); while (age 130) { JOptionPane.showMessageDialog(null, "An invalid age was entered. Please try again."); inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); } 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 What is the problem with this loop? 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 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++; } 4 4 Which of these blocks exhibit off-by-one error?

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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." + "You must enter at least one character."); } Using a break inside loops is generally considered a bad idea.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Confirmation Dialog JOptionPane.showConfirmDialog(null, /*prompt*/ "Play Another Game?", /*dialog title*/ "Confirmation", /*button options*/ JOptionPane.YES_NO_OPTION);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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. 4 th Ed Chapter for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } Syntax for the for Statement for ( ; ; ) 1) Initialization 2) Boolean Expression 4) Increment and back to 2) 3) (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 The Formatter Class We use the Formatter class to format the output. Formatter formatter = new Formatter(System.out); 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 Control Strings Alternatively, we can use : System.out.format(,,, … ) Integers % d Real Numbers %. f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Using the Date Class Here's one way to measure the execution time Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Problem Statement Problem statement: Write an application that will play Hi-Lo games with the user. The objective of the game is for the user to guess the computer- generated secret number in the least number of tries. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number. The maximum number of tries allowed for each game is six. The user can play as many games as she wants.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Overall Plan Tasks: do { Task 1: generate a secret number; Task 2: play one game; } while ( the user wants to play );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Example Program Write a program to read a list of exam scores (integer percentages in the range 0 to 100) and to output the total number of grades and the number of grades in each letter-grade category (90 to 100 = A, 80 to 89 = B, 70 to 79 = C, 60 to 69 = D, and 0 to 59 = F). The end of the input is indicated by a negative score as a sentinel value. (The negative value isused only to end the loop, so do not use it in the calculations).