Tutorial 10
The instructor’s notes for this tutorial will consist of the following:
This tutorial covers the repetition structure. Included is the proper design of a repetition structure using flowcharts and/or pseudocode, as well as the actual implementation of the repetition structure in C++ using the while statement. As with the selection structure, nesting repetition structures is also covered. Integrated with the repetition structure is the concept of initializing and updating counters and accumulators.
After completing the tutorial, the student will be able to:
Introduction to the repetition structure
The repetition structure, also called a loop, is one of the three basic control structures used in programming. The other two control structures are sequence and the selection structure, which have been covered in previous tutorials. The repetition structure is used when you would like the program to repeatedly process one or more program instructions until some condition is met, at which time the repetition structure ends.
While the concept of a repetition structure is quite simple, it is important to properly design the repetition structure. Both flowcharts and pseudocode have been covered previously (review if necessary), and you will remember that the diamond symbol represents a decision and is called the selection/repetition symbol. (This symbol was introduced with the selection structure in the previous tutorials). Each diamond has one flowline entering the symbol, and two flowlines leaving the symbol. The two flowlines leaving the symbol represent the true and false paths and should be marked accordingly. See page 343 for an example of a flowchart containing a repetition structure.
Even though flowcharts are commonly used in representing repetition structures, many programmers still wish to use pseudocode. You should always use whichever design method is most effective for you. Many programmers will use a combination of flowcharts and pseudocode. Different programming structures may lend themselves to being designed in either a flowchart or pseudocode. See page 342 for an example of a repetition structure in pseudocode.
Components of the repetition structure
A repetition structure can either be a pretest loop or posttest loop. In a pretest loop, the loop condition is evaluated before the instructions within the loop are processed, while in a posttest loop, the evaluation occurs after the instructions within the loop are processed. Of the two types of loops, the pretest loop is the most commonly used. You will cover the pretest loop in this tutorial. The posttest loop will be covered in Appendix C.
With very rare exceptions, every loop has a loop condition and a loop body. The loop condition appears at the beginning of a pretest loop and determines the number of times the instructions within the loop, referred to as the loop body, will be processed. Similar to a selection structure condition, a loop condition must result in either a true or false value (a boolean value). When the loop condition evaluates to true, the one or more instructions listed in the loop body are processed. If the loop condition evaluates to false, the instructions listed in the loop body are skipped over and control is passed to the next statement after the loop.
Because the loop condition in a pretest loop is evaluated before any of the instructions within the loop are processed, it is possible that the loop body instructions may not be processed. This would be true if the loop condition is initially evaluated to false. Unless the loop has been properly primed (an initial value read to test the loop condition), more than likely this will be the case.
The input instruction(s) that appears just previous to the pretest loop is referred to as the priming read, because it is used to prime (prepare) the loop. The priming read gets only the first value(s) from the user. The input instruction(s) that appear within the loop get the remaining values. Some loops require the user to enter a special value, called a sentinel value, to end the loop. You should use a sentinel value that is easily distinguishable from the valid data the user will enter. Note that other loops may be terminated by the program itself, through the use of a counter.
Counters and accumulators are used within a repetition structure to calculate subtotals, totals, and averages. All counters and accumulators must be initialized and updated. Counters are updated by a constant value, whereas accumulators are updated by an amount that varies.
Coding the repetition structure
Most programming languages offer two forms of the repetition structure: while and do-while. While this tutorial will cover only the while form of the selection structure, the do-while form of the selection structure will be covered in Appendix C. The while statement is used to code the repetition structure in C++. The syntax of the C++ while statement is listed below:
while (loop condition)
one statement, or block of statements enclosed in braces,
to be processed as long as the loop condition is true
//end while
Notice following the keyword while, the loop condition is enclosed in parentheses. This is required in C++, unlike some other languages. Immediately following is the body of the loop, which is the one statement, or block of statements in braces, to be processed as long as the loop condition is true. As with the selection and decision structures, the //end while statement is not mandatory. However, it is very good programming practice and should be coded to aid in the readability and maintainability of the program.
See Figure 10-10 on page 346 which codes a C++ program, including a while statement, from an algorithm in an IPO chart.
Counters and accumulators
Counters and accumulators are used within a repetition structure to calculate subtotals, totals, and averages. A counter is a numeric variable used for counting something, while an accumulator is a numeric variable used for accumulating (adding together) something.
Two tasks are associated with counters and accumulators, initializing and updating. Initializing means to assign a beginning value to the counter or accumulator. Although the beginning value usually is zero, counters and accumulators can be initialized to any number (dependent upon your algorithm). The initialization is usually performed outside the loop body in a program, because it needs to be done only once.
Updating, also called incrementing, means adding a number to the value stored in the counter or accumulator (the number can be positive or negative). A counter is always incremented by a constant value, where an accumulator is incremented by a value that varies. The assignment statement that updates a counter or an accumulator is placed within the loop body in a program, because the update task must be performed each time the loop body instructions are processed.
See the example in Figure 10-11 on page 348 for an example program using counters and accumulators.
Infinite loops
An infinite loop (or endless loop) is a loop that processes its instructions indefinitely. When dealing with the repetition structure, one reason infinite loops occur is that the loop condition continues to be true. Remember that as long as the loop condition is true, the loop body is continually processed. Usually at the end of the loop body a variable is updated that will change the outcome of the loop condition. If this variable is not updated (the statement(s) are left out of the program), then the loop condition will not change. Therefore the loop will continue to be processed indefinitely.
Usually, you can stop a program that contains an infinite loop by pressing Ctrl-C. You can also use the DOS window’s close button.
Counter-controlled pretest loops
As mentioned previously, some loops are terminated by the program itself, through the use of a counter. In other words we can use a counter to count the number of times a loop is processed. For example, if you would like to print your name to the screen ten times, you could begin by initializing a loop counting variable to one. Your loop condition is this case would be to check to see when this loop counting variable would be greater than ten. The loop body would consist of printing your name, followed by incrementing the loop counting variable by one. The loop would continue until your name was printed the tenth time, and the loop counting variable being incremented to eleven. At this point the loop would terminate.
Another name for creating a loop that processes a set of code (loop body) a set amount of times is called iteration.
Nesting loops
You can nest repetition structures similar to the way you can nest selection structures. For repetition structures to be nested and work correctly, the entire inner loop must be contained within the outer loop. Remember from the discussion about nesting selection structures, to follow proper indentation rules, as well as being consistent with your programming style. Coding comments at the end of each loop can also make the code very readable and easy to understand.
Discussion Topics/Additional Activities
1. c a pretest 9. d while (age >= 0)
2. a a diamond 10. a & b sequence and selection
3. d counter 11. a & c sequence and repetition
4. c updated 12. a & b sequence and selection
5. b Counters, accumulators 13. a, b, & c sequence, selection, & repetition
6. d numEmployees = numEmployees +1; 14. c sentinel
7. c total = total + sales; 15. c priming
8. d all of the above
Solutions to Concept Lesson Exercises
Note that the answers to exercises 5, 6, 13-16,and 18 may vary
1.
//T10ConE01.cpp - displays the number entered by the user #include <iostream> using namespace std; int main() { //declare variable int quantity = 0; cout << "Type a number and press the Enter key. (Enter a negative number to stop.): "; cin >> quantity; //perform loop while (quantity >= 0) { cout << "You typed the number " << quantity << endl; cout << "Type a number and press the Enter key. (Enter a negative number to stop.): "; cin >> quantity; }//end while cout << "Loop stopped because you typed the number " << quantity << endl; return 0; } //end of main function
|
2.
//T10ConE02.cpp - displays the character entered by the user #include <iostream> using namespace std; int main() { //declare variable char more = ' '; cout << "Type a character and press the Enter key. (Enter N or n to stop.): "; cin >> more; //perform loop while (more != 'N' && more != 'n') { cout << "You typed the character " << more << endl; cout << "Type a character and press the Enter key. (Enter N or n to stop.): "; cin >> more; }//end while cout << "Loop stopped because you typed the character " << more << endl; return 0; } //end of main function
|
3.
//T10ConE03.cpp - displays the number entered by the user #include <iostream> using namespace std; int main() { //declare variable int number = 0; cout << "Type a number and press the Enter key. (Enter a negative number or 0 to stop.): "; cin >> number; //perform loop while (number > 0) { cout << "You typed the number " << number << endl; cout << "Type a number and press the Enter key. (Enter a negative number or 0 to stop.): "; cin >> number; }//end while cout << "Loop stopped because you typed the number " << number << endl; return 0; } //end of main function |
4.
//T10ConE04.cpp - displays the total sales #include <iostream> using namespace std; int main() { //declare variables char anotherSale = ' '; int salesAmount = 0; int totalSales = 0; cout << "Do you want to enter a sales amount (Y or N)? "; cin >> anotherSale; //perform loop while (anotherSale == 'Y' || anotherSale == 'y') { cout << "Enter the sales amount: "; cin >> salesAmount; totalSales = totalSales + salesAmount; cout << "Do you want to enter another sales amount (Y or N)? "; cin >> anotherSale; }//end while cout << "Total sales: " << totalSales << endl; return 0; } //end of main function
|
5.
//T10ConE05.cpp - displays Hello 10 times #include <iostream> using namespace std; int main() { //declare variable int count = 1; //perform loop while (count <= 10) { cout << "Hello" << endl; count = count + 1; }//end while return 0; } //end of main function
|
6.
//T10ConE06.cpp - displays a series of even numbers #include <iostream> using namespace std; int main() { //declare variable int count = 10; //perform loop while (count < 100) { cout << count * 2 << endl; count = count + 10; }//end while return 0; } //end of main function
|
7. The following numbers will appear on the screen when the code is processed: 0, 1, 2, 3, and 4. The temp
variable will contain the number 5 when the loop stops.
temp |
0 1 2 3 4 5 |
8. The following numbers will appear on the screen when the code is processed: 0, 2, and 4. The totEmp variable
will contain the number 6 when the loop stops.
totEmp |
0 2 4 6 |
9. numStudents = numStudents + 1;
10. quantity = quantity + -5;
(or)
quantity = quantity – 5;
11.
total = total + sales;12. total = total + gross;
13.
//T10ConE13.cpp - displays a pattern of asterisks #include <iostream> using namespace std; int main() { //declare variables int outer = 0; int inner = 0; //perform loops outer = 2; while (outer <= 12) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer + 2; cout << endl; }//end while return 0; } //end of main function |
14.
//T10ConE14.cpp - displays a pattern of asterisks #include <iostream> using namespace std; int main() { //declare variables int outer = 0; int inner = 0; //perform loops outer = 9; while (outer > 0) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer - 1; cout << endl; }//end while return 0; } //end of main function |
15.
//T10ConE15.cpp - displays a pattern of asterisks #include <iostream> using namespace std; int main() { //declare variables int outerEnd = 0; int outerInc = 0; int outer = 0; int inner = 0; //get maximum number of asterisks and increment value cout << "Maximum number of asterisks: "; cin >> outerEnd; cout << "Increment value: "; cin >> outerInc; //perform loops outer = outerInc; while (outer <= outerEnd) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer + outerInc; cout << endl; }//end while return 0; } //end of main function
|
16.
//T10ConE16.cpp - displays a pattern of asterisks #include <iostream> using namespace std; int main() { //declare variables int outer = 0; int inner = 0; int startWith = 0; cout << "Start with 9 asterisks or 1 asterisk? "; cin >> startWith; if (startWith == 9) { outer = 9; //perform loops while (outer > 0) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer - 1; cout << endl; inner = 1; }//end while } else { outer = 1; //perform loops while (outer <= 9) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer + 1; cout << endl; inner = 1; }//end while } return 0; } //end of main function
|
17. In this exercise, the student learns how to stop an endless (infinite) loop. The student does not make any
changes to the original T10ConE17.cpp file.
18.
//T10ConE18.cpp - displays a pattern of asterisks #include <iostream> using namespace std; int main() { //declare variables int outer = 0; int inner = 0; char process = 'Y'; //perform loops while (process == 'Y' || process == 'y') { outer = 2; while (outer <= 12) { inner = 1; while (inner <= outer) { cout << "*"; inner = inner + 1; }//end while outer = outer + 2; cout << endl; }//end while cout << "Process again? (Y or N) "; cin >> process; }//end while return 0; } //end of main function |
19. Changes made to the code are shaded.
int num = 1; while (num < 5) { cout << num << endl; num = num + 1; } //end while |
20. Changes made to the code are shaded.
float sales = 0.0; cout << "Enter a sales amount: "; cin >> sales; while (sales > 0) { cout << "Commission: " << sales * .1 << endl; cout << "Enter a sales amount: "; cin >> sales; }//end while |
Solutions to Application Lesson Exercises
1.
//T10AppE01.cpp - displays the grade for one or more students #include <iostream> using namespace std; //function prototypes int getPointsEarned(); char assignGrade(int); int main() { //declare variables int totalEarned = 0; char grade = ' '; char another = 'Y'; while (another == 'Y' || another == 'y') { //get total points earned totalEarned = getPointsEarned(); //assign grade grade = assignGrade(totalEarned); //display grade cout << "Grade: " << grade << endl; cout << "Display another student's grade? "; cin >> another; }//end while
return 0; } //end of main function //*****program-defined functions***** int getPointsEarned() { //gets and accumulates the scores, then returns the total int score = 0; int total = 0; cout << "Enter the first score: "; cin >> score; while (score >= 0) { total = total + score; cout << "Enter the next score: "; cin >> score; }//end while return total; } //end of getPointsEarned function
char assignGrade(int points) { //assigns the letter grade char letterGrade = ' '; if (points >= 360) letterGrade = 'A'; else if (points >= 320) letterGrade = 'B'; else if (points >= 280) letterGrade = 'C'; else if (points >= 240) letterGrade = 'D'; else letterGrade = 'F'; //end ifs return letterGrade; } //end of assignGrade function |
2.
IPO Chart:
Input |
Processing |
Output |
sales
|
Processing items: counter Algorithm:
enter the sales add the sales to the total sales add 1 to the counter end repeat while |
total sales |
Desk-check table:
sales |
count |
total |
0 2000 3000 2500 1500 0 39000 45000 25000 56000 |
0 1 2 3 4 5 0 1 2 3 4 5 |
0 2000 5000 7500 9000 0 39000 84000 109000 165000 |
//T10AppE02.cpp - displays the total monthly sales #include <iostream> using namespace std; int main() { //declare variables int sales = 0; int count = 0; int total = 0; //set counter to 1 count = 1; //get and accumulate sales while (count <= 4) { cout << "Enter sales: "; cin >> sales; total = total + sales; count = count + 1; }//end while
//display total sales cout << "Total sales: $" << total << endl; return 0; } //end of main function |
3.
//T10AppE03.cpp - displays the total monthly and quarterly sales #include <iostream> using namespace std; int main() { //declare variables int sales = 0; int regionCount = 0; int monthCount = 0; int monthTotal = 0; int qtrTotal = 0; //set month counter to 1 monthCount = 1; while (monthCount <= 3) { //set region counter to 1 regionCount = 1; //get and accumulate sales while (regionCount <= 4) { cout << "Enter sales: "; cin >> sales; monthTotal = monthTotal + sales; regionCount = regionCount + 1; }//end while
//display total monthly sales cout << "Total sales for the month: $" << monthTotal << endl; //update quarterly accumulator qtrTotal = qtrTotal + monthTotal; //update month counter monthCount = monthCount + 1; //reset month accumulator monthTotal = 0; }//end while //display total quarterly sales cout << "Total sales for the quarter: $" << qtrTotal << endl; return 0; } //end of main function |
4.
IPO Chart:
Input |
Processing |
Output |
ID
|
Processing items: none Algorithm:
ID 1234 display Sue Nguyen 1345 display Janice Blackfeather 3456 display Allen Kraus 4567 display Margie O’Donnell Other display "Incorrect ID – Please try again" enter the ID end repeat while |
name |
Desk-check table:
id |
0 1345 4567 -1 |
//T10AppE04.cpp - displays a name #include <iostream> using namespace std; int main() { //declare variable int id = 0; //get the ID cout << "Enter an ID (enter -1 to stop the program): "; cin >> id;
while (id != -1) { //display the name switch (id) { case 1234: cout << "Sue Nguyen" << endl; break; case 1345: cout << "Janice Blackfeather" << endl; break; case 3456: cout << "Allen Kraus" << endl; break; case 4567: cout << "Margie O'Donnell" << endl; break; default: cout << "Incorrect ID - Please try again" << endl; }//end switch //get the ID cout << "Enter an ID (enter -1 to stop the program): "; cin >> id; }//end while return 0; } //end of main function |
5.
IPO Chart:
Input |
Processing |
Output |
number registered |
Processing items: charge Algorithm:
if (the number registered <= 3) charge = 150 * number registered else if (the number registered <= 9) charge = 100 * number registered else charge = 90 * number registered end ifs add charge to total charge add number registered to total registered enter the number registered end repeat while |
total registered total charge average charge |
Desk-check table:
numReg |
charge |
totNumReg |
totCharge |
avgCharge |
0 3 12 9 -1 |
0 450 1080 900 |
0 3 15 24 |
0 450 1530 2430 |
0.0 101.25 |
//T10AppE05.cpp - displays registration information #include <iostream> using namespace std; int main() { //declare variables int numReg = 0; int charge = 0; int totNumReg = 0; int totCharge = 0; float avgCharge = 0.0; //get number registered cout << "Enter number registered: "; cin >> numReg; while (numReg > 0) { //calculate charge if (numReg <= 3) charge = 150 * numReg; else if (numReg <= 9) charge = 100 * numReg; else charge = 90 * numReg; //end ifs
//update accumulators totCharge = totCharge + charge; totNumReg = totNumReg + numReg; //get number registered cout << "Enter number registered: "; cin >> numReg; }//end while
//display registration information cout << fixed; cout.precision(2); cout << "Total registered: " << totNumReg << endl; cout << "Total charge: $" << totCharge << endl; cout << "Average charge: $" << float(totCharge) / totNumReg << endl; return 0; } //end of main function |
6.
//T10AppE06.cpp - displays the price of a concert ticket #include <iostream> using namespace std; int main() { char location = ' ';
//enter input data cout << "Enter the seat location (9 to stop the program): "; cin >> location; while (location != '9') { //display ticket price if (location == 'B' || location == 'b') cout << "Ticket price: $75" << endl; else if (location == 'P' || location == 'p') cout << "Ticket price: $30" << endl; else if (location == 'L' || location == 'l') cout << "Ticket price: $21" << endl; else cout << "Invalid location" << endl; //end ifs cout << "Enter the seat location (9 to stop the program): "; cin >> location; }//end while return 0; } //end of main function |
7.
//T10AppE07.cpp - displays the number of vacation weeks due an employee #include <iostream> using namespace std; int main() { int years = 0; int totEmp = 0;
//enter input data cout << "Enter the years employed (negative number to stop the program): "; cin >> years; while (years >= 0) { //display vacation weeks if (years == 0) cout << "Vacation weeks: 0" << endl; else if (years <= 5) cout << "Vacation weeks: 1" << endl; else if (years <= 10) cout << "Vacation weeks: 2" << endl; else cout << "Vacation weeks: 3" << endl; //end ifs totEmp = totEmp + 1; //enter input data cout << "Enter the years employed (negative number to stop the program): "; cin >> years; }//end while cout << "Total employees entered: " << totEmp << endl; return 0; } //end of main function |
8.
//T10AppE08.cpp - displays a student's grade #include <iostream> using namespace std; //function prototypes void getPointsEarned(int &); void assignGrade(int, char &); int main() { //declare variables int totalEarned = 0; char grade = ' ';
//get total points earned getPointsEarned(totalEarned); //assign grade assignGrade(totalEarned, grade); //display grade cout << "Grade: " << grade << endl;
return 0; } //end of main function //*****program-defined functions***** void getPointsEarned(int &total) { //gets and accumulates the scores int score = 0; cout << "Enter the first score: "; cin >> score; while (score >= 0) { total = total + score; cout << "Enter the next score: "; cin >> score; }//end while } //end of getPointsEarned function void assignGrade(int points, char &letterGrade) { //assigns the letter grade if (points >= 360) letterGrade = 'A'; else if (points >= 320) letterGrade = 'B'; else if (points >= 280) letterGrade = 'C'; else if (points >= 240) letterGrade = 'D'; else letterGrade = 'F'; //end ifs } //end of assignGrade function |
9.
//T10AppE09.cpp - gets 5 test scores, then displays number of students passing the test #include <iostream> using namespace std; int main() { //declare variables int score = 0; int counter = 0; int totalPass = 0; counter = 5; while (counter != 0) { //get score cout << "Enter test score: "; cin >> score; //count passing score if (score >= 70) totalPass = totalPass++; //end if
//update student counter counter = counter--; }//end while
//display total number of students passing the test cout << "Total students passing test: " << totalPass << endl; return 0; } //end of main function |
10. Changes to the original code are shaded.
//T10AppE10.cpp - displays the squares of the numbers from 1 to 5 #include <iostream> #include <cmath> using namespace std; int main() { //declare variables int number = 1; while (number <= 5) { //display squares cout << pow(number, 2) << endl; number = number + 1; }//end while return 0; } //end of main function |
11. Changes to the original code are shaded.
//T10AppE11.cpp - displays the number of positive and negative integers #include <iostream> using namespace std; int main() { //declare variables int number = 0; int positive = 0; int negative = 0; //get a number cout << "Enter an integer: "; cin >> number; while (number != 0) { //update counters if (number > 0) positive = positive + 1; else negative = negative + 1; //end if //get a number cout << "Enter an integer: "; cin >> number; }//end while
//display counters cout << "Total positive numbers: " << positive << endl; cout << "Total negative numbers: " << negative << endl; return 0; } //end of main function |