Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5. Looping.

Similar presentations


Presentation on theme: "Chapter 5. Looping."— Presentation transcript:

1 Chapter 5. Looping

2 5.1 The Increment and Decrement Operators
++ and -- are operators that add and subtract one from their operands. Num = Num + 1; Num += 1; Num++;

3 Program 5-1 // This program demonstrates the increment and decrement
// operators. #include <iostream.h> void main(void) { int BigVal = 10, SmallVal = 1; cout << "BigVal is " << BigVal << " and SmallVal is " << SmallVal << endl; SmallVal++; BigVal--;

4 cout << "BigVal is " << BigVal
Program continues cout << "BigVal is " << BigVal << " and SmallVal is " << SmallVal << endl; ++SmallVal; --BigVal; }

5 Program Output BigVal is 10 and SmallVal is 1 BigVal is 9 and SmallVal is 2 BigVal is 8 and SmallVal is 3

6 Program 5-2 #include <iostream.h> void main(void) {
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; }

7 Program Output BigVal starts as 10 and SmallVal starts as 1
Now BigVal is: 9 Now SmallVal is: 2 --BigVal: 8 ++SmallVal: 3

8 Using ++ and -- in Mathematical Expressions
B = 5; C = A * B++; cout << A << “ “ << B << “ “ << C; Results:

9 Using ++ and -- in Relational Expressions
if ( X++ > 10) cout << “X is greater than 10.\n”; Two operations are happening: the value in X is tested to determine if it is greater than 10 then X is incremented

10 5.2 Introduction to Loops - The while Loop
A loop is part of a program that repeats. A while loop is a “pre test” loop - the expression is tested before the loop is executed while (expression) statement;

11 Program 5-3 // This program demonstrates a simple while loop.
#include <iostream.h> void main(void) { 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; }

12 Program Output with Example Input
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]

13 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);

14 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

15 5.3 Counters A counter is a variable that is incremented or decremented each time a loop iterates.

16 Program 5-4 // This program displays the numbers 1 through 10 and
// their squares.  #include <iostream.h> void main(void) { int Num = 1; cout << "Number Number Squared\n"; cout << " \n"; while (Num <= 10) cout << Num << "\t\t" << (Num * Num) << endl; Num++; }

17 Program Output Number Number Squared

18 Program 5-5 // This program displays the numbers 1 through 10 and
// their squares. #include <iostream.h>  void main(void) { int Num = 0; cout << "Number Number Squared\n"; cout << " \n"; while (Num++ < 10) cout << Num << "\t\t" << (Num * Num) << endl; }

19 Program Output Number Number Squared

20 5.4 Letting the User Control the Loop
Loops can be designed to repeat until the user enters a particular value.

21 Program 5-6 // This program averages a set of test scores for multiple
// students. It lets the user decide how many.  #include <iostream.h> void main(void) { 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.precision(2);

22 Program continues 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"; }

23 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: [Enter] The average is 79. Student 2: [Enter] The average is   Student 3: [Enter] The average is

24 5.5 Keeping a Running Total
A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an accumulator.

25 Program 5-7 // This program takes daily sales figures over a period of time // and calculates their total.  #include <iostream.h> void main(void) { int Days, Count = 0; float Total = 0.0; cout << "For how many days do you have sales figures? "; cin >> Days;

26 Program continues while (Count++ < Days) { float Sales; cout << "Enter the sales for day " << Count << ": "; cin >> Sales; Total += Sales; } cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The total sales are $" << Total << endl;

27 Program Output with Example Input
For how many days do you have sales figures? 5 [Enter] Enter the sales for day 1: [Enter] Enter the sales for day 2: [Enter] Enter the sales for day 3: [Enter] Enter the sales for day 4: [Enter] Enter the sales for day 5: [Enter] The total sales are $

28 5.6 Sentinels A sentinel is a special value that marks the end of a list of values.

29 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 <iostream.h>  void main(void) { 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\n"; cout << "finished.\n";

30 cout << "The total points are " << Total << endl;
Program continues while (Points != -1) { Count++; cout << "Enter the points for game " << Count << ": "; cin >> Points; if (Points != -1) Total += Points; } cout << "The total points are " << Total << endl;

31 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

32 5.7 The do-while Loop and for Loops
In addition to the while loop, C++ also offers the do-while and for loops. A do-while loop is similar to a while loop, but in post-test format: do statement; while (expression);

33 Program 5-9 #include <iostream.h> void main(void) {
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"; cout << "Do you want to average another set? (Y/N) "; cin >> Again; } while (Again == 'Y' || Again == 'y'); }

34 Program Output with Example Input
Enter 3 scores and I will average them: [Enter] The average is 80. Do you want to average another set? (Y/N) y [Enter] Enter 3 scores and I will average them: [Enter] The average is Do you want to average another set? (Y/N) n [Enter]

35 Program 5-10 // 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.h> void main(void) { int Choice, Months; float Charges; cout.setf(ios::fixed | ios::showpoint); cout.precision(2);

36 Program continues 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; }

37 Program continues switch (Choice) { case 1: Charges = Months * 40.00; cout << "The total charges are $"; cout << Charges << endl; break; case 2: Charges = Months * 20.00; case 3: Charges = Months * 30.00;

38  Program continues case 4: cout << "Thanks for using this "; cout << "program.\n"; break; default: cout << "The valid choices are 1-4. "; cout << "Try again.\n"; } } while (Choice != 4); }

39 Program Output with Example Input
Health Club Membership Menu   1. Standard Adult Membership 2. Child Membership 3. Senior Citizen Membership 4. Quit the Program Enter your choice: 1 [Enter] For how many months 12 [Enter] The total charges are $   Health Club Membership Menu   1. Standard Adult Membership 2. Child Membership 3. Senior Citizen Membership 4. Quit the Program Enter your choice: 4 [Enter] Thanks for using this program.

40 The for Loop Ideal for situations that require a counter because it has built-in expressions that initialize and update variables. for (initialization; test; update) statement;

41 Program 5-11 // This program displays the numbers 1 through 10 and
// their squares. #include <iostream.h> void main(void) { int Num; cout << "Number Number Squared\n"; cout << " \n"; for (Num = 1; Num <= 10; Num++) cout << Num << "\t\t" << (Num * Num) << endl; }

42 Program Output Number Number Squared

43 Omitting the for Loop’s Expressions
int Num = 1; for ( ; Num <= 10; Num++) cout << Num << “\t\t” << (Num * Num) << endl;

44 Program 5-12 // This program takes daily sales figures for one week
// and calculates their total. #include <iostream.h> void main(void) { 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 " << Count << ": ";

45 cout.setf(ios::fixed | ios::showpoint);
Program continues cin >> Sales; Total += Sales; } cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The total sales are $" << Total << endl;

46 Program Output with Example Input
Enter the sales for day 1: [Enter] Enter the sales for day 2: [Enter] Enter the sales for day 3: [Enter] Enter the sales for day 4: [Enter] Enter the sales for day 5: [Enter] Enter the sales for day 6: [Enter] Enter the sales for day 7: [Enter] The total sales are $

47 5.8 Focus on Software Engineering: Deciding Which Loop to Use
The while Loop A pre-test loop. Use when you do not want the loop to iterate if the condition is false from the beginning. Ideal if you want to use a sentinel. The do-while Loop A post-test loop. Use if you always want the loop to iterate at least once. The for Loop Automatically executes an update expression at the end of each iteration. Ideal for situations where a counter variable is needed. Used when the exact number of required iterations is known.

48 5.9 Focus on Software Engineering: Nested Loops
A loop that is inside another loop is called a nested loop.

49 Program 5-13 // This program averages test scores. It asks the user for the // number of students and the number of test scores per student. #include <iostream.h> void main(void) { 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;

50 Program continues for (int Count1 = 1; Count1 <= NumStudents; Count1++) { Total = 0; for (int Count2 = 1; Count2 <= NumTests; Count2++) int Score; cout << "Enter score " << Count2 << " for "; cout << "student " << Count1 << ": "; cin >> Score; Total += Score; } Average = Total / NumTests; cout << "The average score for student " << Count1; cout << " is " << Average << ".\n\n";

51 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.

52 5.10 Breaking Out of a Loop The break statement causes a loop to terminate early.

53 Program 5-14 // This program raises the user's number to the powers
// of 0 through 10. #include <iostream.h> #include <math.h> void main(void) { 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";

54 Program continues 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; }

55 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]

56 5.11 The continue Statement
The continue statement causes a loop to stop its current iteration and begin the next one.

57 Program 5-15 // This program calculates the charges for video rentals.
// Every third video is free. #include <iostream.h> #include <iomanip.h> void main(void) { int VideoCount = 1, NumVideos; float Total = 0.0; char Current; cout << "How many videos are being rented? "; cin >> NumVideos;

58 Program continues 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);

59 Program continues cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The total is $" << Total; }

60 Program Output with Example Input
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

61 5.12 Using Loops for Input Validation
Loops can be used to create input routines that repeat until acceptable data is entered.

62 Program 5-16 // 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 do-while loops. #include <iostream.h> void main(void) { int Players, Max, NumTeams, LeftOver; do cout << "What is the maximum number of players "; cout << "per team? "; cin >> Max;

63 Program continues if (Max < 9 || Max > 15)
{ cout << "You should have at least 9 but no\n"; cout << "more than 15 per team.\n"; } } while (Max < 9 || Max > 15);   do { cout << "How many players are available? "; cin >> Players; if (Players < 0) cout << "Please enter a positive number.\n"; } while (Players < 0); NumTeams = Players / Max; LeftOver = Players % Max; cout << "There will be " << NumTeams << " teams with\n"; cout << LeftOver << " players left over.\n";

64 Program Output with Example Input
What is the maximum number of players per team? 4 [Enter] You should have at least 9 but no more than 15 per team. What is the maximum number of players per team? 12 [Enter] How many players are available? -142 [Enter] Please enter a positive number How many players are available? 142 [Enter] There will be 11 teams with 10 players left over.


Download ppt "Chapter 5. Looping."

Similar presentations


Ads by Google