1.13k likes | 1.35k Views
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures
E N D
In this chapter, you will: • Learn about repetition (looping) control structures • Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures • Examine break and continue statements • Discover how to form and use nested control structures
WHY IS REPETITION NEEDED? • Suppose we want to add five numbers (say to find their average). • From what you have learned so far, you could proceed as follows. cin>>num1>>num2>>num3>>num4>>num5; sum = num1+num2+num3+num4+num5; average = sum/5; • Suppose we wanted to add and average 100, or 1000, or more numbers. • We would have to declare that many variables, and list them again in cin statement, and perhaps, again in the output statement.
Suppose the numbers we want to add are the following: 5 3 7 9 4 • Consider the following statements. 1. sum = 0; 2. cin>>num; 3. sum = sum + num; • Assume sum and num are variables of the type int. • The first statement initializes sum to 0. • Execute statements 2 and 3. • Statement 2 stores 5 in num and statement 3 updates the value of sum by adding num to it. • After statement 3 the value of sum is 5.
Let us repeat statements 2 and 3. • After statement 2 num = 3 • After statement 3 sum = sum + num = 5 + 3 = 8. • At this point sum contains the sum of first two numbers. • Repeat statements 2 and 3 (that is, third time). • After statement 2 num = 7 • After statement 3 sum = sum + num = 8 + 7 = 15 • Now sum contains the sum of first three numbers. • If we repeat statements 2 and 3 two more times, sum will contain the sum of all five numbers.
To add 10 numbers, you can repeat statements 2 and 3 10 times. • To add 100 numbers we can repeat statements 2 and 3 100 times. • You would not have to declare any addition variables as in the first code. • There are three repetition or looping structures in C++ that lets us repeat statements over and over until certain conditions are met.
THE whileLOOPING (REPETITION) STRUCTURE The general form of the while statement is while(expression) statement • In C++, while is a reserved word. • The statement can be either a simple or compound statement. • The expression acts as a decision maker and is usually a logical expression. • The statement is called the body of the loop. • Note that the parentheses around the expression are part of the syntax.
The expression provides an entry condition. • If the expression initially evaluates to true, the statement executes. • The loop condition—the expression—is then reevaluated. If it again evaluates to true, the statement executes again. • The statement (body of the loop) continues to execute until the expression is no longer true. • A loop that continues to execute endlessly is called an infinite loop. • To avoid an infinite loop, make sure that the loop’s body contains statement(s) that assure that the exit condition—the expression in the while statement—will eventually be false.
Example 5-1 i = 0; //Line 1 while(i <= 20) //Line 2 { cout<<i<<" "; //Line 3 i = i + 5; //Line 4 } Output: 0 5 10 15 20
At Line 1, the variable i is set to 0. • The expression in the while statement (at Line 2), i <= 20, is evaluated. Since the expression i <= 20 evaluates to true, the body of the while loop executes next. • The body of the while loop consists of the statements at Lines 3 and 4. • The statement at Line 3 outputs the value of i, which is 0. • The statement at Line 4 changes the value of i to 5. • After executing the statements at Lines 3 and 4, the expression in the while loop (at Line 2) is evaluated again. • Since i is 5, the expression i <= 20 evaluates to true and the body of the while loop executes again. • This process of evaluating the expression and executing the body of the while loop continues until the expression, i < 20 (at Line 2), no longer evaluates to true. • The variable i (Line 2) in the expression is called the loop control variable.
a. Within the loop i becomes 25, but is not printed since the entry condition is false. b. If we omit the statement i = i + 5; from the body of the loop, we have an infinite loop, continually printing rows of zeros. c. The loop control variable in the while statement must be initialized before entry. If the statement i = 0; (at Line 1) is omitted, the loop may not execute at all. (Recall that variables in C++ are not automatically initialized.)
d.In the above program segment if the two statements in the body of the loop are interchanged, it may very well cause a drastic alteration in the result. i = 0; while(i <= 20) { i = i + 5; cout<<i<<" "; } Output: 5 10 15 20 25
Example 5-2 i = 20; //Line 1 while(i < 20) //Line 2 { cout<<i<<" "; //Line 3 i = i + 5; //Line 4 } Here no values will be output.
Case 1: Counter-Controlled whileLoops counter = 0; while(counter < N) { . . . counter++; . . . }
Example 5-3 Suppose the input is 12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8 The first number, 12, specifies the number of values there are to be.
// Program: AVG1 #include <iostream> using namespace std; int main() { int limit; // store the number of items // in the list int number; // variable to store the number int sum; // variable to store the sum int counter; // loop control variable cout<<"Line 1: Enter data for processing" <<endl; //Line 1 cin>>limit; //Line 2 sum = 0; //Line 3 counter = 0; //Line 4
while(counter < limit) //Line 5 { cin>>number; //Line 6 sum = sum + number; //Line 7 counter++; //Line 8 } cout<<"Line 9: The sum of "<<limit <<" numbers = "<<sum<<endl; //Line 9 if(counter != 0) //Line 10 cout<<"Line 11: The average = " <<sum / counter<<endl; //Line 11 else//Line 12 cout<<"Line 13: No input."<<endl; //Line 13 return 0; }
Sample Run: The user input is in red. Line 1: Enter data for processing 12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8 Line 9: The sum of 12 numbers = 335 Line 11: The average = 27
Case 2: Sentinel ControlledwhileLoop cin>>variable; while(variable != sentinel) { . . . cin>> variable; . . . }
Example 5-4 Suppose you want to read some positive integers and average them, but you do not have a preset number of data items in mind. Suppose the number –999 marks the end of data.
//Program: AVG2 #include <iostream> using namespace std; const int SENTINEL = -999; int main() { int number; // variable to store the number int sum = 0; // variable to store the sum int count = 0; // variable to store the total // number read cout<<"Line 1: Enter numbers ending with " <<SENTINEL<<endl; //Line 1 cin>>number; //Line 2 while(number != SENTINEL) //Line 3 { sum = sum + number; //Line 4 count++; //Line 5 cin>>number; //Line 6 }
cout<<"Line 7: The sum of "<<count <<" numbers is "<<sum<<endl; //Line 7 if(count != 0) //Line 8 cout<<"Line 9: The average is " <<sum / count<<endl; //Line 9 else//Line 10 cout<<"Line 11: No input."<<endl; //Line 11 return 0; } Sample Run: The user input is in red. Line 1: Enter numbers ending with -999 34 23 9 45 78 0 77 8 3 5 -999 Line 7: The sum of 10 numbers is 282 Line 9: The average is 28
Example 5-5: Telephone Digits //***************************************************** // Program: Telephone Digits // This is an example of a sentinel-controlled loop. This // program converts uppercase letters to their // corresponding telephone digits. //****************************************************** #include <iostream> using namespace std; int main() { char letter; //Line 1 cout<<"This program converts uppercase " <<"letters to their corresponding " <<"telephone digits."<<endl; //Line 2 cout<<"To stop the program enter Q or Z."<<endl; //Line 3
cout<<"Enter a letter--> "; //Line 4 cin>>letter; //Line 5 cout<<endl; //Line 6 while(letter != 'Q' && letter != 'Z' ) //Line 7 { cout<<"The letter you entered is ---> " <<letter<<endl; //Line 8 cout<<"The corresponding telephone " <<"digit is --> "; //Line 9 if(letter >= 'A' && letter <= 'Z') //Line 10
switch(letter) //Line 11 { case 'A': case 'B': case 'C': cout<<"2\n"; //Line 12 break; //Line 13 case 'D': case 'E': case 'F': cout<<"3\n"; //Line 14 break; //Line 15 case 'G': case 'H': case 'I': cout<<"4\n"; //Line 16 break; //Line 17 case 'J': case 'K': case 'L': cout<<"5\n"; //Line 18 break; //Line 19 case 'M': case 'N': case 'O': cout<<"6\n"; //Line 20 break; //Line 21 case 'P': case 'R': case 'S': cout<<"7\n"; //Line 22 break; //Line 23 case 'T': case 'U': case 'V': cout<<"8\n"; //Line 24 break; //Line 25 case 'W': case 'X': case 'Y': cout<<"9\n"; //Line 26 }
else//Line 27 cout<<"You entered a bad letter."<<endl; //Line 28 cout<<"\nEnter another uppercase letter to be" <<" \nconverted to the corresponding " <<"telephone digits."<<endl<<endl; //Line 29 cout<<"To stop the program enter Q or Z." <<endl<<endl; //Line 30 cout<<"Enter a letter--> "; //Line 31 cin>>letter; //Line 32 cout<<endl; //Line 33 }//end while return 0; }
Sample Run: The user input is in red. This program converts uppercase letters to their corresponding telephone digits. To stop the program enter Q or Z. Enter a letter--> A The letter you entered is ---> A The corresponding telephone digit is --> 2 Enter another uppercase letter to be converted to the corresponding telephone digits. To stop the program enter Q or Z. Enter a letter--> D The letter you entered is ---> D The corresponding telephone digit is --> 3 Enter another uppercase letter to be converted to the corresponding telephone digits. To stop the program enter Q or Z. Enter a letter--> Q
Case 3: Flag-Controlled whileLoops • A flag controlled while loop uses a Boolean variable to control the loop. Suppose found is a Boolean variable. The flag controlled while loop takes the form: found = false; while(!found) { . . . if(expression) found = true; . . . }
Case 4: EOF Controlled while Loop An input stream variable, such as cin,returns a value, after reading data, as follows: 1. If the program has reached the end of input data, the input stream variablereturns the logical value false. 2. If the program reads a faulty data (such as char into int), the input stream enters into the fail state. Once a stream has entered the fail state, any further I/O operations using that stream are considered to be null operations, that is, they have no effect at all. Unfortunately for us the computer does not halt the program or give any error messages. The computer just continues executing the program, silently ignoring each additional attempt to use that stream. In this case cin returns the value false. 3. In cases other than (1) and (2), it returns the logical value true.
The value returned by cin can be used to determine if the program has reached the end of input data. • Since cin returns a logical value true or false, in a while loop it can be considered a logical expression.
An example of an EOF controlled while loop is: cin>>variable; while(cin) { . . . cin>>variable; . . . }
The eof Function • In addition to checking the value of an input stream variable, such as cin, to determine whether the end of file has been reached, the function eof with an input stream variable can also be used to determine the end of file status. • Like the I/O functions, such as get, ignore, and peek, the function eof is also a member of data type istream. The syntax to use the function eof is: istreamVar.eof() where istreamVar is an input stream variable, such as cin.
Suppose we have the following declaration: ifstream infile; Consider the expression: infile.eof() • This is a logical (Boolean) expression. • The value of this expression is true if the program has read past the end of the input file, infile, otherwise the value of this expression is false. • This method of determining the end of file status works best if the input is text. • The earlier method of determining the end-of-file status works better if the input consists of numeric data.
Suppose we have the declaration: ifstream infile; char ch; infile.open("inputDat.dat"); • The following while loop continues to execute as long as the program has not reached the end of file. infile.get(ch); while(!infile.eof()) { cout<<ch; infile.get(ch); }
As long as the program has not reached the end of the input file, the expression infile.eof() is false and so the expression !infile.eof() in thewhilestatementistrue. • When the program reads past the end of the input file, the expression infile.eof() becomestrueandso the expression !infile.eof() inthewhilestatement will becomefalseand the loop terminates.
PROGRAMMING EXAMPLE: CHECKING ACCOUNT BALANCE A local bank in your town is looking for someone to write a program that calculates a customer’s checking account balance at the end of each month. The data is stored in a file in the following form: 467343 23750.40 W 250.00 D 1200 W 75.00 I 120.74 . . .
The first line of data shows the account number followed by the account balance at the beginning of the month. • Thereafter each line has two entries: the transaction code and the transaction amount. • The transaction code W or w means withdrawal, D or d means deposit, and I or i means interest paid by the bank. • The program updates the balance after each transaction. • During the month, if at any time the balance goes below $1000.00, a $25.00 service fee is charged. • The program prints the following information: account number, balance at the beginning of the month, balance at the end of the month, interest paid by the bank, total amount of deposit, number of deposits, total amount of withdrawal, number of withdrawals, and service charge if any.
Input: A file consisting of data in the above format. Output: The output is of the following form: Account Number: 467343 Beginning Balance: $23750.40 Ending Balance: $24611.49 Interest Paid: $366.24 Amount Deposited: $2230.50 Number of Deposits: 3 Amount Withdrawn: $1735.65 Number of Withdrawals: 6
Problem Analysis and Algorithm Design • The first entry in the input file is the account number and the beginning balance. • The program first reads the account number and the beginning balance. • Thereafter, each entry in the file is of the following form: transactionCode transactionAmount
To determine the account balance at the end of the month, you need to process each entry that contains the transaction code and transaction amount. • Begin with the starting balance and then update the account balance after processing each entry. • If the transaction code is D, d, I or i, the transaction amount is added to the account balance. • If the transaction code is W or w, the transaction amount is subtracted from the balance. • Since the program also outputs the number of withdrawals and deposits, you need to keep separate counts of withdrawals and deposits. • This discussion translates into the following algorithm:
1. Declare the variables. 2. Initialize the variables. 3. Get the account number and beginning balance. 4. Get the transaction code and transaction amount. 5. Analyze the transaction code and update the appropriate variables. 6. Repeat Steps 4 and 5 until there is no more data. 7. Print the result.
Variables acctNumber //variable to store account number beginningBalance //variable to store //beginning balance accountBalance //variable to store //account balance at the //end of the month amountDeposited //variable to store total //amountdeposited numberOfDeposits //variable to store the //number of deposits amountWithdrawn //variable to store total //amountwithdrawn numberOfWithdrawals //variable to store number //of withdrawals interestPaid //variable to store interest //amountpaid
int acctNumber; double beginningBalance; double accountBalance; double amountDeposited; int numberOfDeposits; double amountWithdrawn; int numberOfWithdrawals; double interestPaid; char transactionCode; double transactionAmount; bool isServiceCharged; ifstream infile; //input file stream variable ofstream outfile; //output file stream variable
Named Constants const double minimumBalance = 1000.00; const double serviceCharge = 25.00;
1. Declare the variables. Declare variables as discussed previously. 2. Initialize the variables. • Initialize the variables amountDeposited, numberOfDepositsamountWithdrawn, numberOfWithdrawals, and interestPaid must be initialized to 0. The variable isServicedCharged is initialized to false. You can initialize these variables when you declare them. • After reading the beginning balance in the variable beginningBalance from the file, initialize the variable accountBalance to the value of the variable beginningBalance. • Since the data will be read from a file, you need to open the input file. The following code opens the files:
infile.open("a:money.txt"); //open input file if(!infile) { cout<<"Cannot open input file"<<endl; cout<<"Program terminates!!!"<<endl; return 1; } outfile.open("a:money.out"); //open input file
3.Get the account number and starting balance. infile>>acctNumber>>beginningBalance; 4. Getthe transaction code and transaction amount. infile>>transactionCode>>transactionAmount;
5. Analyze thetransaction code and update the appropriate variables switch(transactionCode) { case 'D': case 'd': accountBalance = accountBalance + transactionAmount; amountDeposited = amountDeposited + transactionAmount; numberOfDeposits++; break; case 'I': case 'i': accountBalance = accountBalance + transactionAmount; interestPaid = interestPaid + transactionAmount; break;
case 'W': case 'w': accountBalance = accountBalance - transactionAmount; amountWithdrawn = amountWithdrawn + transactionAmount; numberOfWithdrawals++; if((accountBalance < minimumBalance) && (!isServiceCharged)) { accountBalance = accountBalance - serviceCharge; isServiceCharged = true; } break; default: cout<<"Invalid transaction code"<<endl; } //end switch