1 / 51

CS102 Introduction to Computer Programming

CS102 Introduction to Computer Programming. Chapter 5 Looping. Chapter 5 Topics. The Increment and Decrement Operators Introduction to Loops The while Loop Counters Letting the User Control a Loop Keeping a Running Total. Sentinels The do-while Loop The for Loop

Télécharger la présentation

CS102 Introduction to Computer Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS102Introduction to Computer Programming Chapter 5 Looping

  2. Chapter 5 Topics • The Increment and Decrement Operators • Introduction to Loops • The while Loop • Counters • Letting the User Control a Loop • Keeping a Running Total • Sentinels • The do-while Loop • The for Loop • Deciding Which Loop to Use • Nested Loops • Breaking Out of a Loop • The continue Statement • Using Loops for Input Validation

  3. Increment and Decrement Operators • Increment means increase by one (Num = Num + 1) = = (Num +=1) = = (Num++) • Decrement means decrease by one (Num = Num - 1) = = (Num -=1) = = (Num--) • ++ and-- are unary operators Prefix mode increment/decrement is done first Postfix mode increment/decrement is done last • Operand must be an lvalue Concept - ++ and -- are operators that add and subtract one from their operands.

  4. // This program demonstrates the increment and decrement operators. #include <iostream> using namespace std; int main() { int BigVal = 10, SmallVal = 1; cout << "BigVal is " << BigVal << " and SmallVal is " << SmallVal << endl; SmallVal++; BigVal--; cout << "BigVal is " << BigVal << " and SmallVal is " << SmallVal << endl; ++SmallVal; --BigVal; cout << "BigVal is " << BigVal << " and SmallVal is " << SmallVal << endl; return 0; } Program 5-1 Program Output BigVal is 10 and SmallVal is 1 BigVal is 9 and SmallVal is 2 BigVal is 8 and SmallVal is 3

  5. #include <iostream> using namespace std; int main(){ int BigVal = 10, SmallVal = 1; cout << "BigVal starts as " << BigVal; cout << " and SmallVal starts as " << SmallVal << endl; cout << "BigVal--: " << BigVal-- << endl; cout << "SmallVal++: " << SmallVal++ << endl; cout << "Now BigVal is: " << BigVal << endl; cout << "Now SmallVal is: " << SmallVal << endl; cout << "--BigVal: " << --BigVal << endl; cout << "++SmallVal: " << ++SmallVal << endl; return 0; } Program Output BigVal starts as 10 and SmallVal starts as 1 BigVal--: 10 SmallVal++: 1 Now BigVal is: 9 Now SmallVal is: 2 --BigVal: 8 ++SmallVal: 3 Program 5-2 Note the difference between Postfix andPre fix

  6. Sample ++ -- operations E. x = 99;if(x++ < 100) cout <<"it is true";else cout <<"it is false"; F. x = 1;if(-- x) cout <<"it is true";else cout <<"it is false"; A. x = 2;y = x++;cout << x <<“,”<< y; B. x = 2;y = ++ x; cout << x <<“,”<< y; C. x = 2;y = 4;cout << x++ <<“,”; cout << --y; D. x = 2;y = 2 * x++;cout << x <<“,”<< y; 3, 2 3 ,3 2 ,3 3 ,4

  7. Loops • A loop is a control structure which can cause a statement or group of statements to repeat while pre-test loop (may never execute) do-while post-test loop (always execute once) for pre-test loop (may never execute) Concept - A loop is a part of a program that can repeat

  8. The while Loop • The expression is tested for true or false • if true, the statements are executed and the test is made again • if false, the loop is exited while (expression) statement; statement body while (number != 99) cin >>number; while (number != 99) { cin >>number; cout << number; } or

  9. while statement flow chart while (expression) Yes Statement body No

  10. while Is a Pre-test Loop • A pre-test loop executes zero or more times • make sure you have a mechanism for terminating the loop. int x = 0; while (x>10) { cout <<"hello"; } Executes zero times int x = 0; while (x<10) { cout <<"hello"; } This is an infinite loop Concept - A pre-test loop evaluates its test-expression before each iteration

  11. // This program demonstrates a simple while loop. #include <iostream> using namespace std; int main() { int Number = 0; cout << "This program will let you enter number after\n"; cout << "number. Enter 99 when you want to quit the "; cout << "program.\n"; while (Number != 99) cin >> Number; return 0; } Program Output This program will let you enter number after number. Enter 99 when you want to quit the program. 1 [Enter] 2 [Enter] 30 [Enter] 75 [Enter] 99 [Enter] Program 5-3

  12. Terminating a Loop A loop that does not have a way of stopping is called an infinite loop int Test = 0; while (Test < 10) cout << “Hello\n”; A null statement is also an infinite loop, but it does nothing forever: while (Test < 10);

  13. Programming Style and the while Loop • If there is only one statement repeated by the loop, it should appear on the line after the while statement and be indented one additional level • If the loop repeats a block, the block should begin on the line after the while statement and each line inside the braces should be indented

  14. Counters • A counter controls the number of iterations that a loop is executed • Make sure the counter is properly initialized • Be careful where the counter increments or decrements. int num = 0; while (num++ <10) {cout <<num; } What will the output look like 12345678910 Concept - a Counter is a variable that regularly increments or decrements each time a loop iterates

  15. // This program displays the numbers 1 through 10 and // their squares. #include <iostream> using namespace std; int main() { int Num = 1; cout << "Number Number Squared\n"; cout << "-------------------------\n"; while (Num <= 10) { cout << Num << "\t\t" << (Num * Num) << endl; Num++; } return 0; } Program Output Number Number Squared -------------------------1 12 43 94 165 256 367 498 649 8110 100 Program 5-4 The increment in this while loop is in the statement body

  16. // This program displays the numbers 1 through 10 and // their squares. #include <iostream> using namespace std; int main() { int Num = 0; cout << "Number Number Squared\n"; cout << "-------------------------\n"; while (Num++ < 10) cout << Num << "\t\t" << (Num * Num) << endl; return 0; } Program Output Number Number Squared -------------------------1 12 43 94 165 256 367 498 649 8110 100 Program 5-5 The increment in this while loop is in the conditional expression

  17. Letting the User Control a Loop • Be careful !! • Range check all inputs • Be sure that data conforms to the specification • Reasonableness check all counters • Check for abnormally large counters and loop controls • Give the user and your program a way out • provide a mechanism for terminating the loop if an error is encountered Concept - Loops can be designed to repeat until the user enters a particular value.

  18. /* This program averages a set of test scores for multiple students. It lets the user decide how many. */ #include <iostream> using namespace std; int main() { int NumStudents, Count = 0; cout << "This program will give you the average of three\n"; cout << "test scores per student.\n"; cout << "How many students do you have test scores for? "; cin >> NumStudents; cout << "Enter the scores for each of the students.\n"; cout << fixed << precision(2); while (Count++ < NumStudents) { int Score1, Score2, Score3; float Average; cout << "\nStudent " << Count << ": "; cin >> Score1 >> Score2 >> Score3; Average = (Score1 + Score2 + Score3) / 3.0; cout << "The average is " << Average << ".\n"; } return 0; } Program 5-6 If the user enters too large a number there is no way to change it

  19. Program Output with Example Input This program will give you the average of three test scores per student. How many students do you have test scores for? 3 [Enter] Enter the scores for each of the students. Student 1: 75 80 82 [Enter] The average is 79. Student 2: 85 85 90 [Enter] The average is 86.67. Student 3: 60 75 88 [Enter] The average is 74.33.

  20. Keeping a Running Total • Define a variable outside the while loop to accumulate the running total • Initialize the variable, usually to zero • Allow the while loop to add to the running total each iteration. • Be careful with how you use the running total when you exit the loop • divide by zero • over flows and underflows Concept - A running total is a sum of numbers that accumulates with each iteration.

  21. /* This program takes daily sales figures over a period of time and calculates their total. */ #include <iostream> using namespace std; int main() { int Days, Count = 0; float Total = 0.0; cout << "For how many days do you have sales figures? "; cin >> Days; while (Count++ < Days) { float Sales; cout << "Enter the sales for day " ; cout << Count << ": "; cin >> Sales; Total += Sales; } cout << precision(2) << fixed << showpoint; cout << "The total sales are $" << Total << endl; reuturn 0; } Program 5-7 Program Output For how many days do you have sales figures? 5 [Enter] Enter the sales for day 1: 489.32 [Enter] Enter the sales for day 2: 421.65 [Enter] Enter the sales for day 3: 497.89 [Enter] Enter the sales for day 4: 532.37 [Enter] Enter the sales for day 5: 506.92 [Enter] The total sales are $2448.15

  22. Sentinels • Provides a mechanism for terminating a loop after an unspecified number of iterations • A sentinel should be a value that would not normally be part of the input list • ie, a negative value for test scores • must be the same data type Concept - A sentinel is a special value that marks the end of a list of values.

  23. Sample Program • This program calculates the average score for each student • It incorporates: • user controlled loops • user inputs the number of students • counters • counts the number of scores entered • sentinels • checks for no more scores

  24. /* 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 <iostream> using namespace std; int main() { int Count = 0, Points = 0, 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"; while (Points != -1) { Count++; cout << "Enter the points for game " ; cout << Count << ": "; cin >> Points; if (Points != -1) Total += Points; } cout << "The total points are " << Total << endl; } return 0; } Program 5-8

  25. Program Output with Example Input Enter the number of points your team has earned so far in the season, then enter -1 when you are finished. Enter the points for game 1: 7 [Enter] Enter the points for game 2: 9 [Enter] Enter the points for game 3: 4 [Enter] Enter the points for game 4: 6 [Enter] Enter the Points for game 5: 8 [Enter] Enter the points for game 6: -1 [Enter] The total points are 34

  26. The do-while Loop • An upside down while loop • must be terminated with a semicolon after the closing parenthesis of the test-expression • The statement block executes at least once • The expression is tested at the end of each iteration • Perfect for controlling menu selections

  27. do while Statement Flow Chart Statement body while (expression) Yes No

  28. /* This program demonstrates the use of a do-while loop*/ #include <iostream> using namespace std; int main() { int Score1, Score2, Score3; float Average; char Again; do { cout << "Enter 3 scores and I will average them: "; cin >> Score1 >> Score2 >> Score3; Average = (Score1 + Score2 + Score3) / 3.0; cout << "The average is " << Average << ".\n"; Program Output Enter 3 scores and I will average them: 80 90 70 [Enter] The average is 80. Do you want to average another set? (Y/N) y [Enter] Enter 3 scores and I will average them: 60 75 88 [Enter] The average is 74.333336.Do you want to average another set? (Y/N) n [Enter] Program 5-9 cout << "Do you want to average another set? (Y/N) "; cin >> Again; } while (Again == 'Y' || Again == 'y'); return 0; }

  29. /* This program displays all of the numbers in a file.*/ #include <iostream> #include <fstream> using namespace std; int main() { int numbers; ifstream inputFile; inputFile.open(“numbers.txt”); if (!inputFile) cout << “Error opening file.\n”; else { inputFile >> number; while (!inputFile.eof() ) { cout << number << endl; inputFile >> number; } inputFile.close() } return 0; } Program 5-10

  30. /* This program displays a menu and asks the user to make a selection. A switch statement determines which item the user has chosen. A do-while loop repeats the program until the user selects item 4 from the menu.*/ #include <iostream> using namespace std; int main() { int Choice, Months; float Charges; cout.setf(ios::fixed | ios::showpoint); cout.precision(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; if (Choice != 4) { cout << "For how many months? "; cin >> Months; } Program 5-12

  31. switch (Choice) { case 1: Charges = Months * 40.00; cout << "The total charges are $"; cout << Charges << endl; break; case 2: Charges = Months * 20.00; cout << "The total charges are $"; cout << Charges << endl; break; case 3: Charges = Months * 30.00; cout << "The total charges are $"; cout << Charges << endl; break; case 4: cout << "Thanks for using this "; cout << "program.\n"; break; default: cout << "The valid choices are 1-4. "; cout << "Try again.\n"; } #end of switch } while (Choice != 4); return 0; } Program continues

  32. Program Output with Example Input Health Club Membership Menu1. Standard Adult Membership2. Child Membership3. Senior Citizen Membership4. Quit the ProgramEnter your choice: 1 [Enter]For how many months 12 [Enter]The total charges are $480.00 Health Club Membership Menu1. Standard Adult Membership2. Child Membership3. Senior Citizen Membership4. Quit the ProgramEnter your choice: 4 [Enter]Thanks for using this program.

  33. The for Loop • for (initialization; test; update) { Place as many statements here as needed; } initialization Yes test Statements update No

  34. Program 5-13 /* This program displays the numbers 1 through 10 and their squares.*/ #include <iostream> using namespace std; int main() { int Num; cout << "Number Number Squared\n"; cout << "-------------------------\n"; for (Num = 1; Num <= 10; Num++) { cout << Num << '\t\t' ; cout<< (Num * Num) << endl; } return 0; } Program Output Number Number Squared -------------------------1 12 43 94 165 256 367 498 649 8110 100

  35. Parts of the for loop • Initialization (an assignment statement) • sets up the counter with a starting value • only done once • Test (a relational expression) • Tests the counter against a specified condition • Update (an assignment statement) • changes the counter by the specified amount • Statements (any valid C++ Statement) • statements executed only if the test results in a true condition.

  36. Examples for (num=1; num< 10; num++) { if (num== 7) continue; cout <<"\nThe count is " <<num; } cin >> savings; for(;savings<1e7;) {cout <<"I still need to work"; cin >> deposit; savings += deposit;} Prints the numbers 1 thru 9 but skips 7 cin >> age; for (num=age; num>0; num--) cout <<"Happy Birthday"; Prints Happy birthday as many times as you are years old Adds deposits to your initial savings account until you have at least a million dollars

  37. // This program takes daily sales figures for one week and calculates their total.*/ #include <iostream> using namespace std; int main() { const int Days = 7; int Count; float Total; for (Count = 1, Total = 0.0; Count <= Days; Count++) { float Sales; cout << "Enter the sales for day "; cout << Count << ": "; cin >> Sales; Total += Sales; } cout << precision(2) << fixed << showpoint; cout << "The total sales are $" << Total << endl; ` return 0; } Program 5-14 Defines and initializes a running total Program Output Enter the sales for day 1: 489.32 [Enter] Enter the sales for day 2: 421.65 [Enter] Enter the sales for day 3: 497.89 [Enter] Enter the sales for day 4: 532.37 [Enter] Enter the sales for day 5: 506.92 [Enter] Enter the sales for day 6: 489.01 [Enter] Enter the sales for day 7: 476.55 [Enter] The total sales are $3413.71

  38. Omitting the for Loop’s Expressions for (int num =1; Num <= 10; Num++) cout << Num << “\t\t” << (Num * Num) << endl; Or int Num = 1; for ( ;; ) { if (Num <= 10) cout << Num << “\t\t” << (Num * Num) << endl; else break; Num++; }

  39. Complex for Loops • Initializing multiple variables; • Any number of variables can be initialized • assignment statements are separated by a , • Logical and relational test conditions • as long as the expression results in true or false • Updating multiple variables • Same as for initializing variables • Variables can be declared within the for loop • limits their scope to the for loop

  40. Deciding Which Loop to Use • while loops are useful when you might not want the loop to execute at all • while you are home answer the phone • do-while loops are useful when the loop must execute at least one time • let the phone ring until it is answered • for loops are useful when you know the number of times the loop must execute • let the phone ring 5 times then hang up

  41. Nested Loops • An inner loop goes through all of its iterations for each iteration of an outer loop • Inner loops complete their iterations faster than outer loops • To get the total number of iterations of a nested loop multiply the number of iterations of all the loops

  42. // This program averages test scores. It asks the user for the number of students and the number of test scores per student.*/ #include <iostream> using namespace std; int main() { int NumStudents, NumTests, Total; float Average; cout << "This program averages test scores.\n"; cout << "For how many students do you have scores? "; cin >> NumStudents; cout << "How many test scores does each student have? "; cin >> NumTests; for (int student = 1; student <= NumStudents; student ++) { Total = 0; 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; } Program 5-15 Outer for loop Inner for loop

  43. Program Output with Example Input This program averages test scores. For how many students do you have scores? 2 [Enter] How many test scores does each student have? 3 [Enter] Enter score 1 for student 1: 84 [Enter] Enter score 2 for student 1: 79 [Enter] Enter score 3 for student 1: 97 [Enter] The average for student 1 is 86. Enter score 1 for student 2: 92 [Enter] Enter score 2 for student 2: 88 [Enter] Enter score 3 for student 2: 94 [Enter] The average for student 2 is 91.

  44. Breaking Out of a Loop • Used to prematurely terminate the execution of a while, do-while or for loop • Same statement used in the switch statement • When the break statement is encountered the program jumps the the next statemetn following the loop. • Gives the user an opportunity to terminate an infinite loop Concept - The break statement causes a loop to terminate early

  45. // This program raises the user's number to the powers of 0 through 10.*/ #include <iostream> #include <math.h> using namespace std; int main() { int Value; char Choice; cout << "Enter a number: "; cin >> Value; cout << "This program will raise " << Value; cout << " to the powers of 0 through 10.\n"; for (int Count = 0; Count < 10; Count++) { cout << Value << " raised to the power of "; cout << Count << " is " << pow(Value, Count); cout << "\nEnter Q to quit or any other key "; cout << "to continue. "; cin >> Choice; if (Choice == 'Q' || Choice == 'q') break; } return 0; } Program 5-16 Allows the loop to be prematurely terminated

  46. Program Output Enter a number: 2 [Enter] This program will raise 2 to the powers of 0 through 10. 2 raised to the power of 0 is 1 Enter Q to quit or any other key to continue. C [Enter] 2 raised to the power of 1 is 2 Enter Q to quit or any other key to continue. C [Enter] 2 raised to the power of 2 is 4 Enter Q to quit or any other key to continue. Q [Enter]

  47. The continue Statement • Any statements that follow the continue are ignored • Execution goes to test portion of the while and do-while and to the update part of the for loop • Can be used to • handle special cases • exclude invalid input from affecting the execution of the loop Concept - The continue statement causes a loop to stop its current iteration and begin the next one.

  48. // This program calculates the charges for video rentals. Every third video is free.*/ #include <iostream> #include <iomanip> using namespace std; int main() { int VideoCount = 1, NumVideos; float Total = 0.0; char Current; cout << "How many videos are being rented? "; cin >> NumVideos; 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 << precision(2) << fixed; cout << "The total is $" << Total; return 0; } Program 5-17 Program Output How many Videos are being rented? 6 [Enter] Is video #1 a current release? y [Enter] Is video #2 a current release? n [Enter] Video #3 is free! Is video #4 a current release? n [Enter] Is video #5 a current release? y [Enter] Video #6 is free! The total is $12.00 Skips this iteration

  49. Program Output with Example Input Program Output How many Videos are being rented? 6 [Enter] Is video #1 a current release? y [Enter] Is video #2 a current release? n [Enter] Video #3 is free! Is video #4 a current release? n [Enter] Is video #5 a current release? y [Enter] Video #6 is free! The total is $12.00

  50. Using Loops for Input Validation • A loop can let the user re-enter data as many times as necessary until the values are in range. • Particularly useful if the program must have valid input in order to continue • Be sure to let the user know what valid data is Concept - A loop can be used to create input routines that repeat until acceptable data is entered.

More Related