Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.

Similar presentations


Presentation on theme: "CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct."— Presentation transcript:

1 CHAPTER 5 CONTROL STRUCTURES II (Repetition)

2 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

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

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

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.

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

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

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

9

10 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

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

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

13 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

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

15 Case 1: Counter-Controlled while Loops counter = 0; while(counter < N) {. counter++;. }

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

17 // Program: AVG1 #include 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

18 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; }

19 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

20 Case 2: Sentinel Controlled while Loop cin>>variable; while(variable != sentinel) {. cin>> variable;. }

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

22 //Program: AVG2 #include 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 }

23 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

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

25 cout ";//Line 4 cin>>letter; //Line 5 cout<<endl;//Line 6 while(letter != 'Q' && letter != 'Z' )//Line 7 { cout " <<letter<<endl; //Line 8 cout<<"The corresponding telephone " ";//Line 9 if(letter >= 'A' && letter <= 'Z')//Line 10

26 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 }

27 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 "; //Line 31 cin>>letter;//Line 32 cout<<endl;//Line 33 }//end while return 0; }

28 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

29 Case 3: Flag-Controlled while Loops 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;. }

30 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 variable returns 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.

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

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

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

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

35 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); }

36 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 the while statement is true. When the program reads past the end of the input file, the expression infile.eof() becomes true and so the expression !infile.eof() in the while statement will become false and the loop terminates.

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

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

39 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

40 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

41 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:

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

43 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 //amount deposited numberOfDeposits//variable to store the //number of deposits amountWithdrawn //variable to store total //amount withdrawn numberOfWithdrawals //variable to store number //of withdrawals interestPaid //variable to store interest //amount paid

44 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

45 Named Constants const double minimumBalance = 1000.00; const double serviceCharge = 25.00;

46 1. Declare the variables. Declare variables as discussed previously. 2. Initialize the variables. Initialize the variables amountDeposited, numberOfDeposits amountWithdrawn, numberOfWithdrawals, and interestPaid must be initialized to 0. T he 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:

47 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

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

49 5. Analyze the transaction 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;

50 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

51 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. Print the result: This is accomplished by using output statements.

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

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

54 //******************************************************* // Program -- Checking Account Balance. // This program calculates a customer’s checking account // balance at the end of the month. //******************************************************* #include 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;

55 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; }

56 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

57 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;

58 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

59 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;

60 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

61 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

62 PROGRAMMING EXAMPLE: FIBONACCI NUMBER Consider the following sequence of numbers, 1, 1, 2, 3, 5, 8, 11, 19, 30,.... Given the first two numbers of the sequence say a 1 and a 2, the nth number a n, n >= 3, of this sequence is given by a n = a n-1 + a n-2. Thus a 3 = a 2 +a 1 = 1 + 1 = 2; a 4 = a 3 + a 2 = 1 + 2 = 3,

63 Such a sequence is called a Fibonacci sequence. In the above sequence a 2 = 1 and a 1 = 1. However, given any first two numbers, we can determined the nt h number, a n, n >= 3, of the sequence. The number determined this way is called the nth Fibonacci number. Suppose a 2 = 6 and a 1 = 3. Then a 3 = a 2 +a 1 = 6 + 3 = 9; a 4 = a 3 + a 2 = 9 + 6 = 15 Input: The first two Fibonacci numbers and the desired Fibonacci number. Output: The n th Fibonacci number.

64 Problem Analysis and Algorithm Design To find, say a 10 the 10th Fibonacci number of a sequence, we first find a 9 and a 8, which will require us to find a 7 and a 6 and so on. Thus, in order to find a 10, first we must find a 3, a 4, a 5,..., a 9. This discussion translates into the following algorithm. 1. Get the first two Fibonacci numbers. 2. Get the desired Fibonacci number. That is, get the position, n, of the Fibonacci number in the sequence. 3. Calculate the next Fibonacci number of the sequence by adding the previous two elements of the Fibonacci sequence. 4. Repeat Step 2 until the n th Fibonacci number has been found. 5. Output the n th Fibonacci number.

65 Variables int previous1; // Variable to store the first // Fibonacci number int previous2, // Variable to store the second // Fibonacci number int current; // Variable to store the // current Fibonacci number int counter; // Loop control variable int nthFibonacci; // Variable to store the // desired Fibonacci number

66 Main Algorithm 1. Prompt the user for the first two numbers, that is, previous1 and previous2. 2. Read (input) the first two numbers into previous1 and previous2. 3. Output the first two Fibonacci numbers. (Echo input.) 4. Prompt the user for the desired Fibonacci number. 5.Read the desired Fibonacci number into nthFibonacci. 6.Since we already know the first two Fibonacci numbers of the sequence, we start with determining the third Fibonacci number. So initialize counter to 3, in order to keep track of the calculated numbers. 7.Calculate the next Fibonacci number. current = previous2 + previous1;

67 8. Assign the value of previous2 to previous1. 9. Assign the value of current to previous2. 10. Increment counter. 11. Repeat Steps 7-10 until the desired Fibonacci number has been calculated: The following while loop executes Step 7-10 and determines the nthFibonacci number. while(counter <= nthFibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; current++; } 12. Output the nthFibonacci number, which is current

68 // Program: nth Fibonacci number #include using namespace std; int main() { //Declare variables int previous1; int previous2; int current; int counter; int nthFibonacci; cout<<"Enter the first two Fibonacci " "; //Step 1 cin>>previous1>>previous2;//Step 2 cout<<"\nThe first two Fibonacci numbers " <<"are "<<previous1<<" and "<<previous2; //Step 3 cout<<"\nEnter the desired Fibonacci " ";//Step 4 cin>>nthFibonacci;//Step 5

69 counter = 3;//Step 6 //Steps 7-10 while(counter <= nthFibonacci) { current = previous2 + previous1;//Step 7 previous1 = previous2;//Step 8 previous2 = current;//Step 9 counter++;//Step 10 } cout<<"\n\nThe "<<nthFibonacci <<"th Fibonacci number is: "<<current <<endl;//Step 12 return 0; }//end main

70 Sample Run:The user input is in red. Sample Run 1: Enter the first two Fibonacci numbers -> 12 16 The first two Fibonacci numbers are 12 and 16 Enter the desired Fibonacci number to be determined ->10 The 10th Fibonacci number is 796. Sample Run 2: Enter the first two Fibonacci numbers -> 1 1 The first two Fibonacci numbers are 1 and 1 Enter the desired Fibonacci number to be determined ->15 The 15th Fibonacci number is 610.

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

72

73  The for loop executes as follows: 1. The initial statement executes. 2. The loop condition is evaluated. a. If the loop condition evaluates to true i. Execute the for loop statement. ii. Execute the update statement (the third expression in the parentheses). 3. Repeat Step 2 until the loop condition evaluates to false.  The initial statement 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 initial statement in the for loop is the first statement to be executed and is executed only once.

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

75 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; }

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

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

78 Some comments on for loops:  If the loop condition is initially false, the loop body does not execute.  The update expression, when executed, changes the value of the loop control variable (initialized by the initial expression), which eventually sets the value of the loop condition to false. The for loop executes indefinitely if the loop condition is always true.  C++ allows you to use fractional values for loop control variables of the double type (or any real data type). Because different computers can give these loop control variables different results, you should avoid using such variables.  A semicolon at the end of the for statement (just before the body of the loop) is a semantic error. In this case, the action of the for loop is empty.  In the for statement, if the loop condition is omitted, it is assumed to be true.

79  In a for statement, you can omit all three statements— initial statement, loop condition, and update statement. The following is a legal for loop: for(;;) cout<<"Hello"<<endl;

80 Example 5-8 1. for(i = 10; i >= 1; i--) cout<<" "<<i; The output is 10 9 8 7 6 5 4 3 2 1 2. The following for loop outputs the first 10 positive odd integers. for(i = 1; i <= 20; i = i + 2) cout<<" "<<i;

81 Example 5-9 (a) for(i = 10; i <= 9; i++) cout<<i<<" ";  In this for loop, the initial statement sets i to 10.  Since initially the loop condition ( i <= 9 ) is false, nothing happens. (b) for(i = 9; i >= 10; i--) cout<<i<<" ";  In this for loop, the initial statement sets i to 9.  Since initially the loop condition (i >= 10) is false, nothing happens.

82 (c) for(i = 10; i <= 10; i++) cout<<i<<" ";  In this for loop, the cout statement executes once. (d) for(i = 1; i <= 10; i++); cout<<i<<" ";  This for loop has no effect on the cout statement.  The semicolon at the end of the for statement terminates the for loop; the action of the for loop is thus empty.  The cout statement is all by itself and executes only once.

83 (e) for(i = 1; ; i++) cout<<i<<" ";  In this for loop, since the loop condition is omitted from the for statement, the loop condition is always true.  This is an infinite loop.

84 Example 5-10  In this example, a for loop reads five numbers and finds their sum and average. sum = 0; for(i = 1; i <= 5; i++) { cin>>newNum; sum = sum + newNum; } average = sum / 5; cout<<"The sum is "<<sum<<endl; cout<<"The average is "<<average<<endl;

85 Example 5-11 // Program: sum first n numbers // This program finds the sum of the first n positive integers. #include using namespace std; int main() { int counter;// loop control variable int sum; // variable to store the sum of numbers int N; // variable to store the number of // first positive integers to be added cout<<"Line 1: Enter the number of positive " <<"integers to be added:"<<endl;//Line 1 cin>>N;//Line 2 sum = 0;//Line 3

86 for(counter = 1; counter <= N; counter++) //Line 4 sum = sum + counter;//Line 5 cout<<"Line 6: The sum of the first "<<N <<" positive integers is "<<sum<<endl; //Line 6 return 0; } Sample Run: In this sample run, the user input is in red. Line 1: Enter the number of positive integers to be added: 100 Line 6: The sum of the first 100 positive integers is 5050

87 PROGRAMMING EXAMPLE: CLASSIFY NUMBERS This program reads a given set of integers and then prints the number of odd and even integers. It also outputs the number of zeros. The program reads 20 integers, but you can easily modify it to read any set of numbers. Input: 20 integers, positive, negative, or zeros. Output: The number of zeros, even, and odd numbers.

88 Problem Analysis and Algorithm Design After reading a number you need to check whether it is even or odd. Suppose the value is stored in number. Divide number by 2 and check the remainder. If the remainder is zero, number is even. Increment the even count and then check whether number is zero. If it is, increment the zero count. If the remainder is not zero, increment the odd count. The program uses a switch statement to decide whether number is odd or even. Suppose that number is odd. Dividing by 2 gives the remainder 1 if number is positive and the remainder –1 if negative.

89 If number is even, dividing by 2 gives the remainder 0 whether number is positive or negative. You can use the mod operator, %, to find the remainder. For example, 6 % 2 = 0, -4 % 2 = 0, -7 % 2 = -1, 15 % 2 = 1. Repeat the preceding process of analyzing a number for each number in the list.

90 This discussion translates into the following algorithm. 1. For each number in the list a. Get the number b. Analyze the number c. Increment appropriate count. 2. Print results.

91 Variables: int counter; //loop control variable int number;//variable to store the number read int zeros;//variable to store the zero count int evens;//variable to store the even count int odds;//variable to store the odd count The variables zeros, evens, and odds need to be initialized to zero and these variables can be initialized when we declare them.

92 Main Algorithm 1. Initialize variables. 2. Prompt the user to enter 20 numbers. 3. For each number in the list a. Read the number b. Output the number (echo input) c. If the number is even { i. Increment the even count. ii. If number is zero, increment the zero count. } otherwise Increment the odd count 4. Print results.

93 1. Initialize the variables. You can initialize the variables zeros, evens, and odds when you declare them. 2. Use an output statement to prompt the user to enter 20 numbers. 3. For Step 3, you can use a for loop to process and analyze the 20 numbers.

94 for(counter = 1; counter <= 20; counter++) { read the number; output number; switch(number % 2) //check the remainder { case 0: increment even count; if(number == 0) increment zero count; break; case 1: case –1: increment odd count; }//end switch }//end for 4. Print the result. Output the value of the variables zeros, evens, and odds.

95 //******************************************************** // Program: Counts zeros, odds, and evens // This program counts the number of odd and even numbers. // The program also counts the number of zeros. //******************************************************** #include using namespace std; const int N = 20; int main () { //Declare variables int counter; //loop control variable int number; //variable to store the new number int zeros = 0; // Step1 int odds = 0; // Step1 int evens = 0; // Step1

96 cout<<"Please enter "<<N<<" integers, " <<"positive, negative, or zeros." <<endl;//Step 2 cout "<<endl; for(counter = 1; counter <= N; counter++) //Step 3 { cin>>number; //Step 3a cout<<setw(5)<< number; //Step 3b //Step 3c switch(number % 2) { case 0: evens++; if(number == 0) zeros++; break; case 1: case -1: odds++; } //end switch } // end for loop

97 cout<<endl; //Step 4 cout<<"There are "<<evens<<" evens, " <<"which also includes "<<zeros <<" zeros"<<endl; cout<<"Total number of odds are: "<<odds<<endl; return 0; } Sample Run: In this sample run, the user input is in red. Please enter 20 integers, positive, negative, or zeros. The numbers you entered are --> 0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54 There are 13 evens, which also includes 6 zeros Total number of odds are: 7

98 THE do … while LOOPING (REPETITION) STRUCTURE The general form of a do...while statement is: do statement while(expression);  In C++, do is a reserved word.  The statement executes first, and then the expression is evaluated.  If the expression evaluates to true, the statement executes again.  As long as the expression in a do...while statement is true, the statement executes.

99  To avoid an infinite loop, you must, once again, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it exits.  The statement can be a simple or a compound statement. If it is a compound statement, it must be enclosed between braces.

100

101 Example 5-12 do { cout<<i<<" "; i = i + 5; } while(i <= 20); The output is: 0 5 10 15 20

102  Because the while and for loop has an entry condition, it may never activate, whereas, the do...while loop, which has an exit condition, always goes through at least once.

103 Example: Consider the following two loops (a) (b) i = 11; while(i <= 10) do { cout<<i<<" "; cout<<i<<" ";; i = i + 5; i = i + 5; } while(i <= 10); In (a), the while loop, produces nothing. In (b) the do...while loop, outputs the number 11.

104 Example 5-14 //******************************************************* // Program: Warning Message // This program reads a value and prints a warning // message, or rings a bell, when a value falls outside // a given range. //******************************************************* #include using namespace std; const int low = 60; const int high = 100; int main () { int pressure; do cin>>pressure; while((pressure > low) && (pressure < high)); cout<<"Help"<<endl; return 0; }

105 BREAK AND CONTINUE STATEMENTS  A break and continue statement alters the flow of control.  The break statement, when executed in a switch structure, provides an immediate exit from the switch structure.  You can use the break statement in while, for, and do...while loops.  When the break statement executes in a repetition structure, it immediately exits from these structures.  The break statement is typically used for two purposes: 1. To exit early from a loop 2. To skip the remainder of the switch structure  After the break statement executes, the program continues to execute with the first statement after the structure.

106 The use of a break statement in a loop can eliminate the use of certain (flag) variables. sum = 0; cin>>num; isNegative = false; while(cin && !isNegative) { if(num < 0) //if number is negative, terminate the loop { cout<<"Negative number found in the data"<<endl; isNegative = true; } else { sum = sum + num; cin>>num; }

107  The following while loop is written without using the variable isNegative : sum = 0; cin>>num; while(cin) { if(num < 0) //if number is negative, terminate the loop { cout<<"Negative number found in the data"<<endl; break; } sum = sum + num; cin>>num; }

108 The continue statement is used in while, for, and do-while structures. When the continue statement is executed in a loop, it skips the remaining statements in the loop and proceeds with the next iteration of the loop. In a while and do-while structure, the expression (that is, the loop-continue test) is evaluated immediately after the continue statement. In a for structure, the update statement is executed after the continue statement, and then the loop condition (that is, the loop-continue test) executes.

109 sum = 0; cin>>num; while(cin) { if(num < 0) { cout<<"Negative number found in the data"<<endl; continue; } sum = sum + num; cin>>num; }

110 NESTED CONTROL STRUCTURES #include using namespace std; int main () { int studentId, testScore, count = 0; cin>>studentId; while(studentId != -1) { count++; cin>>testScore; cout<<"Student Id = "<<studentId<<", test score = " <<testScore<<", and grade = ";

111 if(testScore >= 90) cout<<"A."<<endl; else if(testScore >= 80) cout<<"B."<<endl; else if(testScore >= 70) cout<<"C."<<endl; else if(testScore >= 60) cout<<"D."<<endl; else cout<<"F."<<endl; cin>>studentId; }// end while cout<<endl<<"Students in class = "<< count<<endl; return 0; }

112 Suppose we want to create the following pattern. * ** *** **** ***** In the first line we want to print one star, in the second line two stars and so on. Since five lines are to be printed, we start with the following for statement. for(i = 1; i <= 5 ; i++) The value of i in the first iteration is 1, in the second iteration it is 2, and so on. We can use the value of i as the limiting condition in another for loop nested within this loop to control the number of starts in a line.

113 for(i = 1; i <= 5 ; i++) { for(j = 1; j <= i; j++) cout<<"*"; cout<<endl; } What pattern does the code produce if we replace the first for statement with the following? for(i = 5; i >= 1; i--)


Download ppt "CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct."

Similar presentations


Ads by Google