1 / 79

Chapter 5

Chapter 5. REPETITION STRUCTURES. Chapter 5. while loops Interactive while loops for loops Nested loops do-while Loops Structured programming with C++ Arrays Structures. Overview. Output 5 “Hello” cout << “Hello” << endl; cout << “Hello” << endl; cout << “Hello” << endl;

ally
Download Presentation

Chapter 5

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 5 REPETITION STRUCTURES Programming Fundamentals

  2. Chapter 5 • while loops • Interactive while loops • for loops • Nested loops • do-while Loops • Structured programming withC++ • Arrays • Structures Programming Fundamentals

  3. Overview • Output 5 “Hello” • cout << “Hello” << endl; • cout << “Hello” << endl; • cout << “Hello” << endl; • cout << “Hello” << endl; • cout << “Hello” << endl; • Output 100 “Hello”

  4. Overview • Input and calculate the sum of 10 student’s grade • float a; float sum = 0; cin >> a; sum = sum + a; cin >>; sum = sum + a; …………………………………

  5. Overview • The program is very long when the number of student increases. • The following two statements are repeated: cin >> a; sum = sum + a;

  6. Overview • C++ provides three different forms of repetition structures: • while structure • for structure • do-while structure • Each of these structures requires a condition that must be evaluated. • The condition can be tested at either (1) the beginning or (2) the end of the repeating section of code. • If the test is at the beginning of the loop, the type of loop is a pre-test loop. • If the test is at the end of the loop, the type of loop is a post-test loop. Programming Fundamentals

  7. while loops The while statement is used for repeating a statement or series of statements as long as a given conditional expression is evaluated to true. The syntax for the while statement: while( condition expression){ statements; } Programming Fundamentals

  8. prints out the numbers from 1 to 10 int count; count = 1; // initialize count cout << count << “ ”; count = count + 1; cout << count << “ ”; count = count + 1; cout << count << “ ”; count = count + 1;

  9. Example 5.2.1 // This program prints out the numbers from 1 to 10 #include <iostream.h> int main() { int count; count = 1; // initialize count while (count <= 10){ cout << count << " "; count++; // increment count } return 0; } The output of the above program: 1 2 3 4 5 6 7 8 9 10 Programming Fundamentals

  10. In the above program, the loop incurs a counter-controlled repetition. Counter-controlled repetition requires: 1)the name of a control variable (the variable count ) 2)the initial value of the control variable ( count is initialized to 1 in this case 3)the condition that tests for the final value of the control variable (i.e., whether looping should continue) ; 4)the increment (or decrement) by which the control variable is modified each time through the loop. Programming Fundamentals

  11. while loops • What does the following code segment do? • int product = 3; while ( product <= 100 ) product = 3 * product;

  12. INTERACTIVE while LOOP • Combining interactive data entry with the while statement produces very adaptable and powerful programs. Example 5.3.1 #include <iostream.h> int main(){ int total, // sum of grades gradeCounter, // number of grades entered grade, // one grade average; // average of grades   total = 0; gradeCounter = 1; // prepare to loop   while ( gradeCounter <= 10 ) { // loop 10 times cout << "Enter grade: "; // prompt for input cin >> grade; // input grade total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter } Programming Fundamentals

  13. // termination phase average = total / 10; // integer division cout << "Class average is " << average << endl; return 0; } The output of the above program: Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 Programming Fundamentals

  14. Fixed count loop and variable condition loop • In addition to where the condition is tested, repeating sections of code are also classified. • In a fixed count loop, the condition is used to keep track of how many repetitions have occurred. In this kind of loops, a fixed number of repetitions are performed, at which point the repeating section of code is exited. • In many situations, the exact number of repetitions are not known in advance. In such cases, a variable condition loop is used. • In a variable condition loop, the tested condition does not depend on a count being achieved, but rather on a variable that can change interactively with each pass through the loop. When a specified value is encountered, regardless of how many iterations have occurred, repetitions stop. Programming Fundamentals

  15. Sentinels • In programming, data values used to indicate either the start or end of a data series are called sentinels. • The sentinels must be selected so as not to conflict with legitimate data values. Example 5.3.2 #include <iostream.h> const int HIGHGRADE = 100; // sentinel value int main() { float grade, total; grade = 0; total = 0; cout << "\nTo stop entering grades, type in any number" << " greater than 100.\n\n"; Programming Fundamentals

  16. cout << "Enter a grade: "; cin >> grade; while (grade <= HIGHGRADE) { total = total + grade; cout << "Enter a grade: "; cin >> grade; } cout << "\nThe total of the grades is " << total << endl; return 0; } • In the above program, the sentinel is the value 100 for the entered grade. Programming Fundamentals

  17. break statement • The break statement causes an exit from the innermost enclosing loop. Example: while( count <= 10) { cout << “Enter a number: “; cin >> num; if (num > 76){ cout << “you lose!\n”; break; } else cout << “Keep on trucking!\n”; count++; } //break jumps to here Programming Fundamentals

  18. continue Statements • The continue statement halts a looping statement and restarts the loop with a new iteration. while( count < 30) { cout << “Enter a grade: “; cin >> grade; if (grade < 0 || grade > 100) continue; total = total + grade; count++; } • In the above program, invalid grades are simply ignored and only valid grades are added to the total. Programming Fundamentals

  19. The null statement • All statements must be terminated by a semicolon. A semicolon with nothing preceding it is also a valid statement, called the nullstatement. Thus, the statement ; is a null statement. • Example: if (a > 0) b = 7; else ; • The null statement is a do-nothing statement. Programming Fundamentals

  20. for LOOPS • Fixed count loop • Counter variable • initialize a counter variable • Condition • update statement

  21. for LOOPS // This program prints out the numbers from 1 to 10 #include <iostream.h> int main() { int count; // counter variable count = 1; // initialize count while (count <= 10){ cout << count << " "; count++; // increment count } return 0; }

  22. for LOOPS

  23. for LOOPS • The for statement is used for repeating a statement or series of statements as long as a given conditional expression evaluates to true. • One of the main differences between while statement and for statement is that in addition to a condition, you can also include code in the for statement -to initialize a counter variable and -changes its value with each iteration • The syntax of the for statement: for ( initialization expression; condition; update statement){ statement(s); } Programming Fundamentals

  24. for LOOPS // This program prints the even number from 1 to 10 #include <iostream.h> int main() { int count; for (count = 1; count <= 10; count = count + 1) cout << count << " "; return 0; } The output of the above program: 1 2 3 4 5 6 7 8 9 10

  25. Example 5.4.1 // This program prints the even number from 2 to 20 #include <iostream.h> int main() { int count; for (count = 2; count <= 20; count = count + 2) cout << count << " "; return 0; } The output of the above program: 2 4 6 8 10 12 14 16 18 20 Programming Fundamentals

  26. Example 5.4.2 In this example, we have to solve the problem: A person invests $1000.00 in a saving account with 10 percent annual interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:   a = p(1 + r)n where p is the original amount invested, r is the annual interest rate and n is the number of years and a is the amount on deposit at the end of the nth year. Programming Fundamentals

  27. #include <iostream.h> #include <iomanip.h> #include <math.h> int main() { double amount, principal = 1000.0, rate = 0.1; cout << "Year” << setw(21) << "Amount on deposit" << endl;   cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(2); for (int year = 1; year <= 10; year++) { amount = principal*pow(1.0 + rate, year); cout << setw(4) << year << setw(21) << amount << endl; } return 0; } Programming Fundamentals

  28. The output of the above program: Year Amount on deposit 1 1050.00 21102.50 31157.62 41215.51 51276.28 61340.10 71407.10 81477.46 91551.33 10                         1628.89 Programming Fundamentals

  29. for LOOPS for ( int i = 1; i <= 100; i++ ) for ( int i = 100; i >= 1; i-- ) for ( int i = 7; i <= 77; i += 7 ) for ( int i = 20; i >= 2; i -= 2 ) for ( int i = 2; i <= 20; i += 3 ) for ( int i = 99; i >= 0; i -= 11 )

  30. for LOOPS • Print outs the number from 10 to 1 • for(int i = 10; i>= 1; i--) cout << i << endl;

  31. for LOOPS • What happens if • for(int i = 10; i>= 1; i++) cout << i << endl;

  32. for LOOPS • Print outs the even number from 20 to 2 • for(int i = 20; i>= 2; i -= 2) cout << i << endl;

  33. do-while LOOPS • Similar to while LOOPS • do..while statement is used to create post-test loops. • The statements in the body of the loop are run at least one time.

  34. do-while LOOPS • The syntax: do { statements; } while (conditional expression); Programming Fundamentals

  35. do-while LOOPS int counter = 1; // initialize counter do { cout << counter << endl; counter++; } while ( counter <= 10 ); // end do...while

  36. Example of do while loop do { cout<< “\nEnter an identification number:”; cin >> idNum; } while (idNum < 1000 | | idNum> 1999); • Here, a request for a new id-number is repeated until a valid number is entered. Programming Fundamentals

  37. A refined version of the above program: do { cout<< “\nEnter an identification number:”; cin >> idNum; if (idNum < 1000 || idNum > 1999) { cout << “An invalid number was just entered\n”; cout << “Please reenter an ID number /n”; } else break; } while (true); Programming Fundamentals

  38. NESTED LOOPS • Print outs 10 lines, each line has 10 “Hello” for(int i = 1; i<=100; i++) { cout << "Hello “; }

  39. NESTED LOOPS for(int i = 1; i<=100; i++) { cout << "Hello “; if(i % 10 == 0) cout << endl; }

  40. NESTED LOOPS for(int i = 1; i<=10; i++){ for(int j = 1; j<= 10; j++) cout << "Hello "; cout << endl; }

  41. NESTED LOOPS • Print out 10 lines • 1 st has one “1” • 2 nd has two “2” • ………………….

  42. NESTED LOOPS for(int i = 1; i<=10; i++){ for(int j = 1; j<= i; j++) cout << i; cout << endl; }

  43. NESTED LOOPS • In many situations, it is convenient to use a loop contained within another loop. Such loops are called nested loops. • Example 5.4.1 #include <iostream.h> int main() { const int MAXI = 5; const int MAXJ = 4; int i, j; for(i = 1; i <= MAXI; i++) // start of outer loop { cout << "\ni is now " << i << endl; for(j = 1; j <= MAXJ; j++) // start of inner loop cout << " j = " << j; // end of inner loop } // end of outer loop Programming Fundamentals

  44. cout << endl; return 0; } The output of the above program: i is now 1 j = 1 j = 2 j = 3 j = 4 i is now 2 j = 1 j = 2 j = 3 j = 4 i is now 3 j = 1 j = 2 j = 3 j = 4 i is now 4 j = 1 j = 2 j = 3 j = 4 i is now 5 j = 1 j = 2 j = 3 j = 4 Programming Fundamentals

  45. STRUCTURED PROGRAMMING WITH C++ • The goto Statement • In C++, goto statement – an unconditional branch, is just a legacy code from C language. • The effect of the goto statement is a change in the flow of control of the program to the first statement after the label specified in the goto statement. • Example: start: // label if (cout > 10) go to end; … … go to start; end: cout << endl; • Note: The goto statement can lead to programs that are more difficult to debug, maintain, and modify. Programming Fundamentals

  46. Structured Programming • During the 1960s, it became clear that the indiscriminate use of transfers of control through goto statements was the root of much difficulty experienced by programmer groups. • The notion of so-called structured programming became almost synonymous with “goto elimination.” • Bohm and Jacopini’s work demonstrated that all programs could be written in terms of only three control structures: -sequence structure -selection structure - repetition structure Programming Fundamentals

  47. A sequence structure • The sequence structure is built into C++. • Unless directed otherwise, the computer executes C++ statements one after the other in the order in which they are written. Programming Fundamentals

  48. C++ provides three types of selection structures: - if statement (single-selection structure) - if-else statement (double-selection structure) - switch statement. (multiple-selection structure) • C++ provides three types of repetition structures: - while statement - do-while statement - for statement • So C++ has only seven control structures: sequence, three types of selection and three types of repetition. Programming Fundamentals

  49. Building programs in good style • Each C++ program is formed by combining as many of each type of control structures as appropriate for the algorithm the program implements. • We will see that each control structure has only one entry point and one exit point. These single-entry/single-exit control structures make it easy to build programs. • One way to build program is to connect the exit point of one control structure to the entry point of the next. This way is called control-structure-stacking. • Another way is to place one control structure inside another control structure. This way is called control-structure-nesting. Programming Fundamentals

  50. Indentation • Consistent applying reasonable indentation conventions throughout your programs greatly improves program readability. We suggest a fixed-size tab of about ¼ inch or three blanks per indent. For example, we indent both body statements of an if..else structure as in the following statement: if (grade >= 60) cout << “Passed”; else cout << “Failed”; Programming Fundamentals

More Related