Going Round and Round: the Repetition Structure Chapter 4.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
CS0004: Introduction to Programming Repetition – Do Loops.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
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.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration (Looping Constructs in VB) Iteration: Groups of statements which are repeatedly executed until a certain test is satisfied Carrying out Iteration.
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.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 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.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Advanced Decisions and Loops Chapter Some Simple Schoolroom Statistics.
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.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 12: How Long Can This Go On?
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Logic and Design Fifth Edition, Comprehensive
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
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.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Using Loops. Goals Understand how to create while loops in JavaScript. Understand how to create do/while loops in JavaScript. Understand how to create.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
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.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Pendalaman Materi Conditional dan Repetition (Pengulangan)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
REPETITION CONTROL STRUCTURE
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
( Iteration / Repetition / Looping )
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.
T. Jumana Abu Shmais – AOU - Riyadh
Chapter 2.1 Repetition.
M150: Data, Computing and Information
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Going Round and Round: the Repetition Structure Chapter 4

4.1 Computers Don’t Get Bored with Repetition

Loop Basics 1.Set a variable equal to 1 2.Begin the loop 3.Test to see if the variable is less than 4. 4.If the variable is less than 4: 5.{ 6.Do some stuff. 7. Increase the value of the variable by Go back to line 3 and start again. 9.} 10.If the condition is no longer true, go to the next line.

Iterations The number of times a task is repeated is important In computer lingo, a single pass through a loop is called a loop iteration. A loop that executes 3 times goes through 3 iterations.

Beware the Infinite Loop! 1.Declare two integer variables, num1 and num2 2.Begin the loop 3.{ 4.Get a number from the user, store it in num1 5.Set num2 = num Display "Hello!" 7.} 8.Repeat until num1 > num2 9.Display “The End” The test condition is impossible to achieve. The loop will run forever.

Don’t Get Trapped in a Loop 1.Declare a string variable, name 2.Set the initial value of name to " " 3.Begin the loop: test if name == "done" 4.{ 5.Ask the user: "Enter your friend's name:" 6.Store the entry in name 7.Display name 8.} 9.Display “The End” The test condition is extremely unlikely to be met, unless the user has a friend named done. The user will be trapped and have to enter names forever.

4.2 Types of Loops

Pre-Test and Post-Test Loops The general form of a pre-test loop is as follows: Is some condition true? If yes, enter the loop:  Test here! { Do some stuff } Program continues The general form of a post-test loop is as follows: Enter the loop: { Do some stuff } Is some condition true? If yes, go back to line 1  Test here! Program continues

Pre-Test and Post-Test Loops

Valid Test Conditions a.If num1 is a numeric variable: num1 >= 100; b.If myChoice is a string variable: myChoice < 3; c.If num2 is a numeric variable: 14 > num2; d.If response is a string variable: response != "no"; e.If num3 is a numeric variable: num3 = 15; Answers: a.valid -- It asks the question, "Is num1 greater than or equal to 100?" and will always be answered by either true or false. b.not valid -- Since myChoice is a string variable, it cannot be less than the integer 3. However, myChoice < "3"; is a valid test condition. c.not valid -- The left side of the condition must always be a variable. d.valid -- The answer to the question, "Is the value of response not the same as the string "no" ? will always be either true or false. e.not valid -- The statement num3 = 15 ; does not ask a question. It is an assignment statement and assigns the value 15 to the variable num3. num3 == 15; is valid.

Generating a Table with a while loop Example function getPlayers() 5. { 6.var player = prompt("Enter the name of a player:"," "); 7.var points = prompt("Enter the points this player has:"," "); 8.document.write(' '); 9.while (player != "done") 10.{ 11.document.write(' '); 12.document.write(' ' + player + ' '); 13.document.write(' ' + points + ' '); 14.document.write(' '); 15.player = prompt("Enter the name of a player or enter 'done' when you're finished:"," "); 16.points = prompt("Enter the points this player has or 0 if finished:"," "); 17. } 18.document.write(' '); 19. } Today's Players 22. Click to enter players' names

The Post-Test do…while Loop The general form of a post-test loop is as follows: Enter the loop: { Do some stuff } Is some condition true? If yes, go back to line 1  Test here! Program continues This loop will always execute at least once! When should you use a post-test loop over a pre-test loop? Depends on the situation. A shopping cart should use a pre-test loop so the customer is not forced to order at least 1 item. A program that only runs when there is at least one entry (such as payroll for a business) might use a post-test loop.

Using a do...while loop for payroll Example function getPay() { 5. document.write(' '); 6. var name = " "; var hours = 0; var rate = 0; var grossPay = 0; var netPay = 0; 7. document.write(' name gross pay net pay '); 8. name = prompt("Enter the first employee's name:"); 9. do { 10. hours = parseFloat(prompt("How many hours did " + name + " work this week?")); 11. rate = parseFloat(prompt("What is " + name + "'s hourly pay rate?")); 12.if ( hours > 40) 13. grossPay = (40 * rate ) + (( hours - 40) * 1.5 * rate ); 14.else 15. grossPay = hours * rate ; netPay = grossPay *.85; 16.document.write(' ' + name + ' $ ' + grossPay + ' $ ' + netPay + ' '); 17. name = prompt("Enter another employee's name or enter 'done' when finished:"); 18. } while ( name != "done") 19. document.write(' '); 20.} Calculate Employees Paychecks 24. You can enter payroll information for all employees. Paychecks are calculated as shown: 25.OUTPUT GOES HERE

Formatting Output The toFixed() Method num.toFixed(x) where num is a numeric variable and x is the number of places to be represented. If num = num.toFixed(2) = 3.14 num.toFixed(5) = num.toFixed(11) =

Payroll Program Output By adding.toFixed(2) to the variables grossPay and netPay in the code in the previous example, the output would now look like this:

Sentinel Controlled Loops: The sentinel is a signal that input is complete Example function getClass() { 5. document.write(' '); 6. var fname = " "; var lname = " "; var id = " "; var username = 0; var course = " "; 7. course = prompt("What is the name of this course?"); 8. document.write(' ' + course + ' '); 9. document.write(' first name last name ID number username '); 10. fname = prompt("Enter one student's first name:"); 11. lname = prompt("Enter the student's last name:"); 12. id = prompt("Enter the student's identification number:"); 13. do { 14. username = fname + id; 15. document.write(' '+fname+' +lname+' +id+' '+username+' '); 16. fname = prompt("Enter another student's first name or enter 'X' when finished:"); 17. lname = prompt("Enter another student's last name or enter 'X' when finished:"); 18. id = prompt("Enter another student's identification number or enter -9 when finished:"); 19. } while (id != -9) 20. document.write(' '); 21.} Create Usernames 25. You can enter each student's name and ID number and this program will create usernames for you

Student ID Program Output Input: Course Name: Introduction to JavaScript Students: Jacques Jolie, ID: 2345 Isabel Torres, ID: 6789 Kevin Patel, ID: 2037 Barbara Chen, ID: 6589 X X, ID: -9

Formatting Output The toLowerCase() and toLowerCase() Methods name.toLowerCase() name.toUpperCase() where name is a string variable If name = “Joey” name.toLowerCase() = “joey” name.toUpperCase() = “JOEY”

Counter-Controlled Loops A counter-controlled loop contains a variable (the counter) that keeps track of the number of passes through the loop (the iterations). When the counter reaches a preset value, the loop is exited. In order for the computer to execute the loop a certain number of times, it must keep track of how many times it goes through the loop.

Using a Counter 1.Define a counter: The counter is a variable. It is always an integer Common variable names for counters are counter, count, i, or j. In some languages words like count or counter can be keywords. Best to name your counter something very simple, like i or j. 2.Initialize the counter: Set the counter to a beginning value. The counter can begin at any integer value—often determined by other factors in the program We will usually set our counter equal to 0 or 1. 3.Increment (or decrement) the counter: To increment by ones: i = i + 1. Use shortcut operators

Shortcut Operators Beginning Value of j Increment/Decrement Expression ShortcutEnding Value of j 1j = j + 1j++ 2 1j = j – 1j-- 0 5j = j + 2j+=2 7 5j = j – 2j-=2 3 4j = j * 3j*=312 4j = j / 2j/=2 2 1j = j + 1++j 2

4.3 The for Loop

General Form: the for statement for (counter = initialValue; test condition; increment/decrement) { body of the loop; } The Initial Value The first statement sets the counter to its initial value. The initial value can be any integer constant, such as 1, 0, 23, or –4. The initial value can also be another numeric variable. The Test Condition The test condition asks the question, “Is the counter within the range specified by this condition?” In a for loop, the test condition is checked at the beginning. After the loop body executes once, the counter is then either incremented or decremented and the test condition is checked again. The test condition is checked each time after the body of the loop has completed. The Increment/Decrement Statement The increment or decrement statement uses shortcut notation.

Examples 1.function countStars() { var i = 0; var starNum = 4; star = (“*"); for (i = 0; i <= starNum; i++) document.write(star + " "); } Output: * * * * * 2.function countStars() { var i = 0; var starNum = 4; star = (“*"); for (i = starNum; i >= 0; i--) document.write(star + " "); } Output: * * * * *

Examples 3.function countStars() { var i = 0; star = (“*"); for (i = 0; i <= 7; i++) document.write(star + " "); } Output: * * * * * * * * 2.function countStars() { var i = 0; star = (“*"); for (i = 1; i < 7; i++) document.write(star + " "); } Output: * * * * * *

4.4 Data Validation

Making Sure the Entry is Positive var bracelets = parseInt(prompt("How many bracelets do you want?"," ")); while (bracelets < 0) { bracelets = prompt("Please enter a positive number. How many bracelets do you want?"," "); } document.write("You are ordering " + bracelets + " bracelets. Thank you!");

The isNaN() Method This method returns true if expression or variable inside () is not a number. Can be combined with previous example to make sure an actual number which is also a positive number is entered. var bracelets = parseInt(prompt("How many bracelets do you want?"," ")); while (isNaN(bracelets) || bracelets < 0) { bracelets = prompt("Please enter a positive number. How many bracelets do you want?"," "); } document.write("You are ordering " + bracelets + " bracelets. Thank you!");

Checking for Integers The parseInt() method will only truncate the decimal part of a floating point number. To check if a user has entered an integer, use the mod operator. If a number is an integer, number % 1 has remainder = 0 Putting it all together: check that a user enters a positive integer: var bracelets = parseInt(prompt("How many bracelets do you want?"," ")); var check = bracelets % 1; while(isNaN(bracelets) || (bracelets < 0) || (check != 0)) { bracelets = prompt("Please enter a positive whole number. How many bracelets do you want?"," "); } document.write("You are ordering " + bracelets + " bracelets. Thank you!");

The charAt() Method The charAt() method returns the character at a specified index in a string (any text that is enclosed in quotes). Each character in the string has an index number. – Every character counts. This includes punctuation, spaces, special characters such as ' or ' & '. – The index begins at 0. For example, the ' c ' in the string “ cat” has index = 0, the ' a ' in “ cat” has index = 1 and the ' t ' in “ cat” has index = 2. The charAt() method can be used to locate a particular character in a string

Examples (a) myName.charAt(0) = 'M';if you have a numeric variable: var j = 4; (b) myName.charAt(3) = 't';(i) myName.charAt(j) = 'y'; (c) myName.charAt(8) = 'r';(j) myName.charAt(j + 2) = 'M'; (d) myName.charAt(10) = ','(k) myAddress.charAt(j - 3) = '2'; (e) myAddress.charAt(1) = '2';(k) myAddress.charAt(j * 2) = 'w'; (f) myAddress.charAt(3) = ' '; (g) myAddress.charAt(8) = 'w'; (h) myAddress.charAt(14) = 'e' Given the following string variables: var myName = "Morty Mort, Jr." var myAddress = "123 Duckwood Terrace";

The length Property The length property returns the length of a string in characters. When you append this property to a variable, the result is the number of characters in the variable, including all punctuation, special characters, and spaces. Each character in the string has an index number. – Every character counts. This includes punctuation, spaces, special characters such as ' or ' & '. – The length of any string is simply how many characters are in the string. For example, the string "cat" has length = 3 and the string "Lee Clark owns a cat!" has length = 21. The length property can be used to tell the programmer how many characters are in any string. To see if a specific character is included in that string, the length property tells how many characters need to be checked or, in programming terms, how many times a loop must iterate.

Examples if myName = “Persephone“ myName.length = 10 if myName = “Amy Ames“ myName.length = 8 if myAddress = “New York, New York 10002“ myAddress.length = 24 if myAddress = “the big oak tree“ myAddress.length = 16