1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
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.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
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.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
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 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
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.
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
Loops and Files. 5.1 The Increment and Decrement Operators.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
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)
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
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.
Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
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
Repetition Control Structure
Chapter 6: Repetition Statements
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
COP 3330 Object-oriented Programming in C++
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping

2 Topics 5.1 The Increment and Decrement Operators 5.2 Introduction to Loops: The while Loop 5.3 Counters 5.4 Letting the User Control a Loop 5.5 Keeping a Running Total 5.6 Sentinels 5.7 Using a Loop to Read Data from a File

3 Topics 5.8 The do-while and for Loops 5.9 Deciding Which Loop to Use 5.10 Nested Loops 5.11 Breaking Out of a Loop 5.12 The continue Statement 5.13 Using Loops for Data Validation

4 5.1 The Increment and Decrement Operators ++ : add one to a variable val++; is the same as val = val + 1; -- : subtract one from a variable val--; is the same as val = val – 1; can be used before (prefix) or after (postfix) a variable: ++val; --val;

5 Prefix vs. Postfix ++ and -- operators can be used in complex statements and expressions prefix ( ++val, --val ): increment or decrement, then return the value of the variable postfix ( val++, val-- ): return the value of the variable, then increment or decrement

6 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

7 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 Example: Program 5-1

What will the following program segments display? a) x=2; y=4; cout<<x++<<--y; b) x=2; y=2*x++; cout<<x<<y 8 c) x=99; if(x++<100) cout<<"It is true"; else cout<<"It is false"; d) x=0; if(++x) cout<<"It is true"; else cout<<"It is false";

9 5.2 Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (repeats) while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }

10 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

11 while Loop Example int val = 5; while (val <= 8) cout << val++ << endl; produces output:

12 while Loop Notes no ; after (expression) while is a pretest loop – expression is evaluated before the loop executes loop must contain code to make expression become false Infinite loop: loop that does not stop Example: program 5-2program 5-2

Counters Counter: variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (loop control variable) Must be initialized before entering loop May be incremented/decremented either inside the loop or in the loop test Example: program 5-3program 5-3

Letting the User Control a Loop Program can be written so that user input determines loop repetition Used when program processes a list of items, and user knows the number of items User is prompted before loop. Their input is used to control number of repetitions

15 Letting the User Control a Loop - Example int num = 1, limit; cout << "Table of squares\n"; cout << "How high to go? "; cin >> limit; cout << "number square\n"; while (num <= limit) {cout << setw(5) << num << setw(6) << num*num << endl; num++; } Example: Program 5-4Program 5-4

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;

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 Example, program 5-6program 5-6

Using a Loop to Read Data from a File eof() member function: returns true when the end of the file has been reached, false otherwise Can be tested in a while loop to continue execution until end of file: while (!infile.eof())... Example, program 5-7program 5-7

The do-while and for Loops do-while : a posttest loop – execute the loop, then test the expression Format: do statement; // or block in { } while (expression); Note ; after (expression)

20 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 Example: prog. 5-8 prog. 5-9

21 for Loop Useful for counter-controlled loop Format: for(initialization; test; update) statement; // or block in { } No ; after 3 rd expression or after )

22 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) (only if test is true) Execute update, then re- evaluate test expression

23 for Loop - Example int sum, num; for (sum=0, num=1; num <= 10; num++) sum += num; cout << "Sum of numbers 1 – 10 is" << sum << endl;

24 for Loop - Modifications Can omit initialization if already done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num; Can declare variables in initialization : int sum = 0; for (int num=0; num <= 10; num++) sum += num; scope of variable num is the for loop

25 for Loop - Modifications Can omit update if done in loop: for (sum = 0, num = 1; num <= 10;) sum += num++; Can omit test – may get infinite loop: for (sum = 0, num = 1; ; num++) sum += num; Example: prog. 5-10

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

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;

28 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. In previous example, inner loop repeats 9 times Example, Prog. 5-11Prog. 5-11

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

The continue Statement The continue statement causes a loop to stop its current iteration and begin the next one 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 Example, prog. 5-12prog. 5-12

Using Loops for Data Validation Can design a loop to repeat execution until valid input is entered: cout << "Enter a test score " << "in the range 0-100: "; cin >> score; while (score 100) {cout << "Score out of range - " << "reenter: "; cin >> score; } Example, prog. 5-13prog. 5-13