Programming with Loops. When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have.

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

Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
COMP 110 Loops Tabitha Peck M.S. February 11, 2008 MWF 3-3:50 pm Philips
©2004 Brooks/Cole Chapter 5 Repetition. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Repetition So far, our programs processed a single set.
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
1 Chapter 5 File Objects and Looping Statements (Some slides have been modified from their original format)
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
COM S 207 While-Loop Statement Instructor: Ying Cai Department of Computer Science Iowa State University
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Java Programming: From the Ground Up
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
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.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS101 Computer Programming I Chapter 4 Extra Examples.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
CS 100 Introduction to Computing Seminar October 7, 2015.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
Efficiently Solving Computer Programming Problems Doncho Minkov Telerik Corporation Technical Trainer.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
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.
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.
Testing Programs with Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Loops A loop is: Java provides three forms for explicit loops:
CSC111 Quick Revision.
Loops.
Chapter 5: Control Structures II
Repetition-Counter control Loop
Topics Introduction to Repetition Structures
CSS 161: Fundamentals of Computing
Logical Operators and While Loops
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.
COMP 110 Loops, loops, loops, loops, loops, loops…
Let’s all Repeat Together
Logical Operators and While Loops
Topics Introduction to Repetition Structures
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 14, 2011
Repetition Statements
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Chapter 3 Debugging Section 3.4
CSS161: Fundamentals of Computing
The while Looping Structure
Presentation transcript:

Programming with Loops

When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have to read in the exam scores for all students in the class, you should write code to read in just one score and repeat it for all students in the class.  If we needed the sum of all the scores we could add each new score as it was entered to a variable containing the sum.

Initializing Statements  An initializing statement just sets a beginning or initial value for a variable to be used later.  If we don’t initialize a variable before it is used, we can’t be sure what value it contains.  For example, in order to be able to sum values into a variable, that variable must be initialized to zero before we begin.

Initializing Statements (cont’d)  You don’t always initialize variables to zero.  For example, for (count = 1,; count <= n; count++ ) { Read a number into the variable next. product = product * next; }

Ending a Loop  If you know the number of iterations required before entering the loop you can use a for loop. Such loops are called count-controlled loops.  One way to end the loop is to ask the user if it’s time to end the loop. This is called ask-before-iterating.  A third way to end a loop is by using a sentinel value.

Ending a Loop Using a Sentinel Value  A sentinel value is a special input value, different from valid input values, that is used to signal the end of the loop.  For example, if you are reading in exam scores and you don’t know how many you have, if you know that no score can be less that zero, you can use a negative value as the sentinel.  Your condition can just say to keep reading scores until you read a negative score. Then you’re done.

Example of Using a Sentinel Value to End a Loop System.out.println(“Enter scores for all students.”); System.out.println(“Enter a negative number after”); System.out.println(“you have entered the scores.”); Scanner keyboard = new Scanner(System.in); double max = keyboard.nextDouble(); double min = max;//The max and min so far are the first score. double next =keyboard.nextDouble(); while (next >= 0) { if (next > max) max = next; if (next < min) min = next; next = keyboard.nextDouble(); } System.out.println(“The highest score is “ + max); System.out.println(“The lowest score is “ + min);

Nested Loop Example do { System.out.println(); System.out.println(“Enter all the scores to be averaged.”); System.out.println(“Enter a negative number after”); System.out.println(“you have entered all the scores.”); sum = 0; numberOfStudents = 0; next = keyboard.nextDouble(); while (next >= 0) { sum = sum + next; numberOfStudents++ next = keyboard.nextDouble(); } if (numberOfStudents > 0) System.out.println(“The average is “ + (sum/numberOfStudents)); else System.out.println(“No scores to average.”); System.out.println(“Want to average another exam?”); System.out.println(“Enter yes or no.”); answer = keyboard.next(); }while (answer.equalsIgnoreCase(“yes”));

Loop Bugs  Programs with loops are more likely to have bugs than simpler programs.  The two most common bugs associated with loops are: Unintended infinite loops Off-by-one errors

Unintended Infinite Loops  If the condition tested to end the loop is incorrectly written, e.g. (a 0), the loop may never end if a starts off with a positive value and during each iteration a is increased.  Be aware that a loop may work correctly for some input values, but become an infinite loop for others. Running one test case may not be enough to insure correctness.

Off-By-One Bugs  These errors are the ones where your loop iterates one to many or one to few times. You may have written the condition as (number < 0) when you really meant (number <= 0).  To reduce the possibility of these errors you should always test at and near the values used in the condition controlling the loop.

Tracing Variables  If your program does not work correctly and it is not clear what the problem is, it is probably a good idea to trace some key variables. That is to watch what happens to them as they are changed when the program executes.  Many systems have built in utilities for tracing variables. If not you can trace them by printing them out from the program, or you can trace your algorithm by hand using pencil and paper.