1 / 58

CHAPTER 5 CONTROL STRUCTURES II (Repetition)

CHAPTER 5 CONTROL STRUCTURES II (Repetition). THE while LOOPING (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.

Download Presentation

CHAPTER 5 CONTROL STRUCTURES II (Repetition)

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. CHAPTER 5CONTROL STRUCTURES II(Repetition)

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

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

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

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

  6. Case 2: Sentinel ControlledwhileLoop cin>>variable; while(variable != sentinel) { . . . cin>> variable; . . . }

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

  8. //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 }

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

  10. 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; . . . }

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

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

  13. An example of an EOF controlled while loop is: cin>>variable; while(cin) { . . . cin>>variable; . . . }

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

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

  16. 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); }

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

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

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

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

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

  22. 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:

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

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

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

  26. Named Constants const double minimumBalance = 1000.00; const double serviceCharge = 25.00;

  27. 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:

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

  29. 3.Get the account number and starting balance. infile>>acctNumber>>beginningBalance; 4. Getthe transaction code and transaction amount. infile>>transactionCode>>transactionAmount;

  30. 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;

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

  32. 6. Repeat Steps 4 and 5 until there is no more data. Since the number of entries in the input file is not known, the program needs an EOF-controlled while loop. 7. Printthe result: This is accomplished by using output statements.

  33. Main Algorithm 1. Declare and initialize the variables. 2. Open the input file. 3. If the input file does not exist, exit the program. 4. Open the output file. 5. To output floating-point numbers in a fixed decimal format with the decimal point and trailing zero, set the manipulators fixed and showpoint. To output floating-point numbers to two decimal places, set the precision to two decimal places. 6. Read accountNumber and beginningBalance. 7. Set accountBalance to beginningBalance. 8. Read transactionCode and transactionAmount.

  34. 9. While (not end of input file) a. If transactionCode is 'D' i. Add transactionAmount to accountBalance ii. Increment numberOfDeposits b. If transactionCode is 'I' i. Add transactionAmount to accountBalance ii. Add transactionAmount to interestPaid c. If transactionCode is 'W' i. Subtract transactionAmount from accountBalance ii. Increment numberOfWithDrawals iii. If (accountBalance < minimumBalance && !isServicedCharged) 1. Subtract serviceCharge from accountBalance 2. Set isServiceCharged to true d. If transactionCode is other than 'D', 'd', 'I', 'i', 'W', or 'w', output an error message. 10. Output the results.

  35. //******************************************************* // Program -- Checking Account Balance. // This program calculates a customer’s checking account // balance at the end of the month. //******************************************************* #include <iostream> #include <fstream> #include <iomanip> using namespace std; const double minimumBalance = 1000.00; const double serviceCharge = 25.00; int main() { //Declare and initialize variables //Step 1 int acctNumber; double beginningBalance; double accountBalance; double amountDeposited = 0.0; int numberOfDeposits = 0;

  36. double amountWithdrawn = 0.0; int numberOfWithdrawals = 0; double interestPaid = 0.0; char transactionCode; double transactionAmount; bool isServiceCharged = false; ifstream infile; ofstream outfile; infile.open("a:Ch5_money.txt"); //Step 2 if(!infile) //Step 3 { cout<<"Cannot open input file"<<endl; cout<<"Program terminates!!!"<<endl; return 1; }

  37. outfile.open("a:Ch5_money.out"); //Step 4 outfile<<fixed<<showpoint; //Step 5 outfile<<setprecision(2); //Step 5 cout<<"Processing data"<<endl; infile>>acctNumber>>beginningBalance; //Step 6 accountBalance = beginningBalance; //Step 7 infile>>transactionCode>>transactionAmount; //Step 8

  38. while(infile) //Step 9 { switch(transactionCode) { case 'D': //Step 9.a case 'd': accountBalance = accountBalance + transactionAmount; amountDeposited = amountDeposited + transactionAmount; numberOfDeposits++; break; case 'I': //Step 9.b case 'i': accountBalance = accountBalance + transactionAmount; interestPaid = interestPaid + transactionAmount; break;

  39. case 'W': //Step 9.c 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

  40. infile>> transactionCode>>transactionAmount; }//end while //Output Results //Step 10 outfile<<"Account Number: "<<acctNumber<<endl; outfile<<"Beginning Balance: $" <<beginningBalance<<endl; outfile<<"Ending Balance: $"<<accountBalance <<endl<<endl; outfile<<"Interest Paid: $"<<interestPaid <<endl<<endl; outfile<<"Amount Deposited: $" <<amountDeposited<<endl; outfile<<"Number of Deposits: "<<numberOfDeposits <<endl<<endl; outfile<<"Amount Withdrawn: $" <<amountWithdrawn<<endl; outfile<<"Number of Withdrawals: " <<numberOfWithdrawals <<endl<<endl;

  41. if(isServiceCharged) outfile<<"Service Charge: $" <<serviceCharge<<endl; return 0; } Sample Run: (Contents of the output file A:Ch5_money.out) 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

  42. Input File: (A:CH5_money.txt) 467343 23750.40 W 250.00 D 1200.00 W 75.00 I 120.74 W 375.00 D 580.00 I 245.50 W 400.00 W 600.00 D 450.50 W 35.65

  43. THE forLOOPING (REPETITION) STRUCTURE The general form of the for statement is for(initial statement; loop condition; update statement) statement • The initialstatement, loopcondition and updatestatement (called for loop control statements) that are enclosed with in the parentheses controls the body (the statement) of the for statement.

  44. The for loop executes as follows: 1. The initialstatement executes. 2. The loop condition is evaluated. a. If the loopcondition evaluates to true i. Execute the for loop statement. ii. Execute the updatestatement (the third expression in the parentheses). 3. Repeat Step 2 until the loopcondition evaluates to false. • The initialstatement usually initializes a variable (called the for loop control variable, or indexed variable). • In C++, for is a reserved word. • As the name implies, the initialstatement in the for loop is the first statement to be executed and is executed only once.

  45. Example 5-6 The following for loop prints the first 10 positive integers: for(i = 1; i <= 10; i++) cout<<i<<" "; • The statement of a for loop may be a simple or a compound statement.

  46. Example 5-7 1. The following for loop outputs the line of text and a star (on separate lines) five times: for(i = 1; i <= 5; i++) { cout<<"Output a line of stars."<<endl; cout<<"*"<<endl; }

  47. 2. for(i = 1; i <= 5; i++) cout<<"Output a line of stars."<<endl; cout<<"*"<<endl; • This loop outputs the line of text five times and the star only once. • The for loop controls only the first cout statement because the two cout statements are not made into a compound statement. • The first cout statement executes five times because the for loop executes five times. • After the for loop executes, the second cout statement executes only once.

  48. 3. The following for loop executes five empty statements: for(i = 1; i <= 5; i++); //Line 1 cout<<"*"<<endl; //Line 2 • The semicolon at the end of the for statement (before the cout statement, Line 1) terminates the for loop. • The action of this for loop is empty.

More Related