Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping."— Presentation transcript:

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

2 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

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

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

6 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

7 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

8 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 5 slide 8 Notes on Increment, Decrement Can be used in expressions: result = num1++ + --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

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

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

11 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

12 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: 5 6 7 8

13 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

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

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

16 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++; }

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

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

19 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;

20 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; }

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

22 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; }

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

24 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; }

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

26 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

27 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;

28 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; }

29 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 )

30 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

31 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;

32 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

33 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;

34 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;

35 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; }

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

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

38 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

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

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

41 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;

42 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; }

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

44 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 9 - 15): "; 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; }

45 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; }

46 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... }


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

Similar presentations


Ads by Google