Copyright 2003 Scott/Jones Publishing 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.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
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.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
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.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
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.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
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.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
 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.
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.
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.
Starting Out with C++: From Control Structures through Objects
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)
CS102 Introduction to Computer Programming Chapter 5 Looping.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Starting Out with C++, 3 rd Edition. My first C++ program #include using namespace std; int main() { cout
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
Chapter 5. Looping.
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 5. Looping.
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
Presentation transcript:

Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide The Increment and Decrement Operators ++ and -- are operators that add (++) or subtract (--) one from their operands. operator function exp. description ++ preincrement ++a increment a by 1; use new value of a in the expression ++ postincrement a++ use current value of a in the expression in which a resides, then increment a by 1 -- predecrement --b decrement b by 1; use new value of b in the expression -- postdecrement b-- use current value of b in the expression in which b resides, then decrement b by 1

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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++;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 6 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 7 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 8 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide Looping ( Repetition or Iteration Structure ) Pre-test loop: while / for Post-test loop: do

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide Introduction to Loops: The while Loop Loop: part of program that may execute more than 1 time (repeats) while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 11 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 12 while Loop Example int val = 5; while (val <= 8) cout << val++ << endl; produces output:

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 13 while Loop Notes no ; after (expression) while is a pre-test loop: expression is evaluated before the loop executes loop must contain code to make expression become false Infinite loop: loop that does not stop

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 16 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++; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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 accumulator while (num <= 10) { sum += num; num++; } cout << "Sum of numbers 1 – 10 is" << sum << endl;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 19 Program 5-8 // This program calculates the total number of points a // soccer team has earned over a series of games. The user // enters a series of point values, then -1 when finished. #include using namespace std; int main() { int game = 1, points, total = 0; cout << "Enter the number of points your team has earned\n"; cout << "so far in the season, then enter -1 when finished\n\n"; cout << "Enter the points for game " << game << ": "; cin >> points;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 20 Program continued from previous slide. while ( points != -1 ) // test for sentinel value { total += points; cout << "Enter the points for game " << ++game << ": "; cin >> points; } cout << "The total points are " << total << endl; return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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() )...

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 22 Program 5-7 // This program displays five numbers in a file. #include using namespace std; int main() { int number, count = 1;// Initialize the loop counter. ifstream inputFile; inputFile.open("numbers.txt");// Open the file. if ( ! inputFile )// Test for file open error. cout << "Error opening file.\n"; else { while (count <= 5) { inputFile >> number;// Read a number. cout << number << endl;// Display the number. count++;// Increment the counter. } inputFile.close();// Close the file. } return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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)...

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 24 Program 5-7 Version 2 - Corrected // This program displays numbers in a file. // EOF condition is true as soon as the last data item is read! #include using namespace std; int main() { int number; ifstream inputFile; inputFile.open("numbers.txt"); // Try to open the file. if ( ! inputFile ) // Test for file open error { cout > number) ) // if no data could be read… { cout > number; // Read a number. cout << number << endl; // Display the number. } inputFile.close(); // Close the file. return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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)

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 26 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 27 Program 5-9 // This program displays a menu and asks the user to make a // selection. A do-while loop repeats the program until the // user selects item 4 from the menu. #include using namespace std; int main() { int choice, months; double charges; cout << fixed << showpoint << setprecision(2); do { cout << "\n\t\tHealth Club Membership Menu\n\n"; cout << "1. Standard Adult Membership\n"; cout << "2. Child Membership\n"; cout << "3. Senior Citizen Membership\n"; cout << "4. Quit the Program\n\n"; cout << "Enter your choice: "; cin >> choice;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 28 Program 5-9 Continued if (choice >= 1 && choice <= 3) { cout << "For how many months? "; cin >> months; switch (choice) { case 1: charges = months * 40.0; break; case 2: charges = months * 20.0; break; case 3: charges = months * 30.0; } // Display the monthly charges. cout << "The total charges are $"; cout << charges << endl; } else if (choice != 4) { cout << "The valid choices are 1 through 4.\n"; cout << "Try again.\n"; } } while (choice != 4); return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 29 for Loop Useful for counter-controlled loop Format: for( initialization; test; update ) statement; // or block in { } No ; after 3 rd expression or after )

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 30 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 31 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;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 32 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 33 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;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 34 Program 5-11 // This program averages test scores. It asks the user for the // number of students and the number of test scores per student. #include using namespace std; int main() { int numStudents,// Number of students numTests,// Number of test per student total;// Accumulator for total scores float average;// Average test score cout << "This program averages test scores.\n"; cout << "For how many students do you have scores? "; cin >> numStudents;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 35 Program 5-11 Continued cout << "How many test scores does each student have? "; cin >> numTests; for (int student = 1; student <= numStudents; student++) { total = 0; // Initialize the accumulator. for (int test = 1; test <= numTests; test++) { int score; cout << "Enter score " << test << " for "; cout << "student " << student << ": "; cin >> score; total += score; } average = total / numTests; cout << "The average score for student " << student; cout << " is " << average << ".\n\n"; } return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide Deciding Which Loop to Use while : pre-test loop; loop body may not be executed at all do-while : post-test loop; loop body will always be executed at least once for : pre-test loop with initialization and upate expression; useful with counters, or if precise number of repetitions is needed

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 38 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 statements in the inner loop is product of number of repetitions of the two loops. In previous example, inner loop statements repeat 9 times

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 41 Program 5-12 // This program calculates the charges for video rentals. // Every third video is free. #include using namespace std; int main() { int videoCount = 1, numVideos; double total = 0.0; char current; cout << "How many videos are being rented? "; cin >> numVideos;

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 42 Program 5-12 Continued do { if ((videoCount % 3) == 0) { cout << "Video #" << videoCount << " is free!\n"; continue; } cout << "Is video #" << videoCount; cout << " a current release? (Y/N) "; cin >> current; if (current == 'Y' || current == 'y') total += 3.50; else total += 2.50; } while (videoCount++ < numVideos); cout << fixed << showpoint << setprecision(2); cout << "The total is $" << total; return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 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; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 44 Program 5-13 // This program calculates the number of soccer teams // that a youth league may create from the number of // available players. Input validation is demonstrated // with while loops. #include using namespace std; int main() { int players, teamPlayers, numTeams, leftOver; // Get the number of players per team. cout << "How many players do you wish per team?\n"; cout << "(Enter a value in the range ): "; cin >> teamPlayers; while (teamPlayers 15) // Validate input. { cout << "You should have at least 9 but no\n"; cout << "more than 15 per team.\n"; cout << "How many players do you wish per team? "; cin >> teamPlayers; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 45 Program 5-13 // Get the number of players available. cout << "How many players are available? "; cin >> players; while (players <= 0) // Validate input. { cout << "Please enter a positive number: "; cin >> players; } // Perform calculations. numTeams = players / teamPlayers; leftOver = players % teamPlayers; cout << "There will be " << numTeams << " teams with "; cout << leftOver << " players left over.\n"; return 0; }

4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 46 Menu Validation Example //Input validation example //Handles an input stream error #include using namespace std; int main() { int choice; cout > choice; while ( choice 4 ) { if ( cin.fail() ) //non-numeric character could not be read! //clear the failure and remove the character from the input buffer { cin.clear(); cin.get(); } cout > choice; } //process the menu selection... }