Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.

Slides:



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

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.
Starting Out with C++, 3 rd Edition 1 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.
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.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
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.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Programming Logic and Design Fifth Edition, Comprehensive
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
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.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
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.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
A First Book of C++ Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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.
Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer Programming -1-
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
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.
Chapter 5: Loops and Files.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 5: Looping Starting Out with C++ Early Objects Eighth Edition
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 6: Repetition Statements
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Increment and Decrement Operators 5.1

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-3 The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix) a variable: ++val; val++;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-4 The Increment and Decrement Operators -- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1; -- can be also used before (prefix) or after (postfix) a variable: --val; val--;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-5 (Program Continues)

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-6

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-7 Prefix vs. Postfix ++ and -- operators can be used in complex statements and expressions In prefix mode ( ++val, --val ) the operator increments or decrements, then returns the value of the variable In postfix mode ( val++, val-- ) the operator returns the value of the variable, then increments or decrements

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-8 Prefix vs. Postfix - Examples int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays it num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-9 Notes on Increment, Decrement Can be used in expressions: result = num num2; Must be applied to something that has a location in memory. Cannot have: result = (num1 + num2)++; Can be used in relational expressions: if (++num > limit) pre- and post-operations will cause different comparisons

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Loops: The while Loop 5.2

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-11 Introduction to Loops: The while Loop Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-12 while Loop – How It Works while (expression) statement; expression is evaluated –if true, then statement is executed, and expression is evaluated again –if false, then the the loop is finished and program statements following statement execute

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-13 The Logic of a while Loop

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-14

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-15 How the Loop in Lines 9 through 13 Works

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-16 Flowchart of the Loop

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-17 while is a Pretest Loop expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { cout << "Hello\n"; number++; }

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-18 Watch Out for Infinite Loops The loop must contain code to make expression become false Otherwise, the loop will have no way of stopping Such a loop is called an infinite loop, because it will repeat an infinite number of times

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-19 An Infinite Loop int number = 1; while (number <= 5) { cout << "Hello\n"; }

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using the while Loop for Input Validation 5.3

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-21 Using the while Loop for Input Validation Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid. The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered.

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-22 Using the while Loop for Input Validation Here's the general approach, in pseudocode: Read an item of input. While the input is invalid Display an error message. Read the input again. End While

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-23 Input Validation Example cout << "Enter a number less than 10: "; cin >> number; while (number >= 10) { cout << "Invalid Entry!" << "Enter a number less than 10: "; cin >> number; }

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-24 Flowchart

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-25 Input Validation Example from Program 5-5

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Counters 5.4

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-27 Counters Counter: a variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (also known as the loop control variable) Must be initialized before entering loop

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-28

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-29

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The do-while Loop 5.5

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-31 The do-while Loop do-while : a posttest loop – execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression)

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-32 The Logic of a do - while Loop

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-33 do - while Example int x = 1; do { cout << x << endl; } while(x < 0); Although the test expression is false, this loop will execute one time because do - while is a posttest loop.

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-34

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-35

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-36 do-while Loop Notes Loop always executes at least once Execution continues as long as expression is true, stops repetition when expression becomes false Useful in menu-driven programs to bring user back to menu to make another choice (see Program 5-8 in the book)

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The for Loop 5.6

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-38 The for Loop Useful for counter-controlled loop General Format: for(initialization; test; update) statement; // or block in { } No semicolon after 3 rd expression or after the )

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-39 for Loop - Mechanics for(initialization; test; update) statement; // or block in { } 1)Perform initialization 2)Evaluate test expression –If true, execute statement –If false, terminate loop execution 3)Execute update, then re-evaluate test expression

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-40 for Loop - Example int count; for (count = 1; count <= 5; count++) cout << "Hello" << endl;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-41 A Closer Look at the Previous Example

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-42 Flowchart for the Previous Example

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-43

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-44

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-45 A Closer Look at Lines 13 through 14 in Program 5-9

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-46 Flowchart for Lines 13 through 14 in Program 5-9

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-47 When to Use the for Loop In any situation that clearly requires –an initialization –a false condition to stop the loop –an update to occur at the end of each iteration

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-48 The for Loop is a Pretest Loop The for loop tests its test expression before each iteration, so it is a pretest loop. The following loop will never iterate: for (count = 11; count <= 10; count++) cout << "Hello" << endl;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-49 for Loop - Modifications You can have multiple statements in the initialization expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Initialization Expression

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-50 for Loop - Modifications You can also have multiple statements in the test expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++, y++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Test Expression

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-51 for Loop - Modifications You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-52 for Loop - Modifications You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop.

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Keeping a Running Total 5.7

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-54 Keeping a Running Total running total: accumulated sum of numbers from each repetition of loop accumulator: variable that holds running total int sum=0, num=1; // sum is the while (num <= 10) // accumulator { sum += num; num++; } cout << "Sum of numbers 1 – 10 is" << sum << endl;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-55 (Program Continues)

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-56

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sentinels 5.8

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-58 Sentinels sentinel: value in a list of values that indicates end of data Special value that cannot be confused with a valid value, e.g., -999 for a test score Used to terminate input when user may not know how many values will be entered

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-59 (Program Continues)

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-60

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a Loop to Read Data from a File 5.9

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-62 Using a Loop to Read Data from a File The stream extraction operator >> returns true when a value was successfully read, false otherwise Can be tested in a while loop to continue execution as long as values are read from the file: while (inputFile >> number)...

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-63

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deciding Which Loop to Use 5.10

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-65 Deciding Which Loop to Use while : pretest loop; loop body may not be executed at all do-while : posttest loop; loop body will always be executed at least once for : pretest loop with initialization and update expression; useful with counters, or if precise number of repetitions is needed

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested Loops 5.11

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-67 Nested Loops A nested loop is a loop inside the body of another loop Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl;

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-68 Lines from Program 5-16

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-69 Nested Loops - Notes Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops.

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Breaking Out of a Loop 5.12

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-71 Breaking Out of a Loop Can use break to terminate execution of a loop Use sparingly if at all – makes code harder to understand and debug When used in an inner loop, terminates that loop only and goes back to outer loop

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The continue Statement 5.13

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1-73 The continue Statement Can use continue to go to end of loop and prepare for next repetition – while, do-while loops: go to test, repeat loop if test passes – for loop: perform update step, then test, then repeat loop if test passes Use sparingly – like break, can make program logic hard to follow