1 / 29

While’s – The Basic Idea

While’s – The Basic Idea. Set of operations is repeated as long as (while) some condition is true. First Year Lifestyle: go to the pub while (you are thirsty) buy a beer drink it end while throw up go home

Download Presentation

While’s – The Basic Idea

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. While’s – The Basic Idea Set of operations is repeated as long as (while) some condition is true. First Year Lifestyle: go to the pub while (you are thirsty) buy a beer drink it end while throw up go home This is a “pre-test” loop. The test is performed before any actions are performed. If you are not thirsty when you arrive at the pub, you will not buy any beer at all. Actions to be repeated as long as the condition is true.

  2. C++ While Loop (1) while (boolean expression) { any number of statements } “Pre-Test” Loop Test Condition Is false Is true Execute Body

  3. C++ While Loop (2) while (boolean expression) { any number of statements } The while statement as shown above is actually the combination of the fundamental C++ while statement (which allows only one statement in the “body” of the loop) and the C++ block statement. If the boolean expression evaluates to true, all of the statements in the body of the loop are exacuted before the condition is tested again. We DO NOT somehow break out out the loop is the condition becomes false part way through the execution of these statements.

  4. A Counting Loop We want a program which reads in ten values and computes their average. Pseudo-code: values_read = 0 sum = 0 while values_read is less than 10 read a value sum = sum + value just read values_read = values_read + 1 end while output sum divided by values_read This is an example of a “counting loop”. We loop until a counter reaches some value. See sample program while1.cpp.

  5. A Sentinel-Controlled Loop We want a program which reads in values until –999 is entered and computes the average of the values entered (excluding the –999). values_read = 0 sum = 0 read a value while value just read is not -999 sum = sum + value just read values_read = values_read + 1 read a value end while if values_read is zero output “no values entered” else output sum divided by values_read endif This is a “sentinal controlled” loop. We loop until some “sentinal value” is entered. See sample program while2.cpp.

  6. Investment Example Given an initial investment ($) and an interest rate (%), we want to know how many years it will take for our investment to reach some target amount ($). Interest is paid anually. Pseudo Code: read investment, interest rate, and target years = 0 while investment is less than the target value // do another year’s worth of calculations compute interest investment = investment + interest years = year + 1 end while output years and final investment value See sample program invest.cpp.

  7. Manipulators (1) • So far output lists have involved just three possibilities: a message (“”), an expression, and endl. The last of these is an example of a “manipulator”. Other possibilities exist. • The following two manipulators control the output of floating point values. • setprecision (integer expression) • specifies the number of digits to be output after the decimal point • setiosflags (ios::fixed | ios::showpoint) • - forces fixed point (as opposed to scientific) notation and specifies that the decimal point is to be displayed even if the fractional part is zero.

  8. Manipulators (2) To output an amount in dollars and cents, one can do the following: cout << setiosflags (ios::fixed | ios::showpoint) << setprecision(2) << “The amount owing is $” << amount_owing << endl; The effects of the setiosflags and setprecision manipulators remain in force until overridden. These manipulators only affect floating point output. To use these manipulators, iomanip.h must be included. Be sure to use only a SINGLE vertical bar in connection with setiosflags.

  9. The “=“ Operator = is an operator, just as +, *, and so on are operators. Somewhat unusual in that it has a side effect: the left hand operand (which must be a variable) acquires the value of the right hand operator. Like all other operators it produces a result. The result of an assignment is the value assigned (the new value of the left hand operand). // not recommended (too tricky), // but both legal and reasonable if ((a = (b + 6))< 5) { . . . // legal, but almost certainly an error // = probably intended to be == if (a = 10) { . . .

  10. The “Expression” Statement The basic C++ statement consists of an expression followed by a semi-colon. This means “evaluate the expression and then throw away the final result”. Because “=“ is an operator, the “assignment statement” is just a special case of this general form. a = b; // an expression and a semi-colon a + b; // legal but useless – results in // “code has no effect” warning The “=“ operator is right associative. This allows assignments of the form shown below. a = b = c = d = 0; // all variables get 0 “d = 0” is performed first, the result of this operation (the value assigned, zero) is then assigned to “c”, and so on.

  11. The ++ and -- Operators ++ and -- is are unary operators (like unary – and !). They may be placed either before the operand (prefix form) or after it (postfix form). They have a side effect: the operand (which must be a variable) is either incremented (++ operator) or decremented (-- operator). The result of the operation is the value of the variable either before (postfix form) or after (prefix form) it is modified. Often used in loops, as shown below. values_read = 0; while (values_read < 10) { . . . values_read++; // expression + semi-colon }

  12. Operator Summary (1)

  13. Operator Summary (2)

  14. The For Loop The “for loop” is a bit of a luxury in that in doesn’t allow us to do anything that can’t be done almost as easily with a while loop. for (i = 0; i < 10; i++) { // statements } is entirely equivalent to i = 0; while (i < 10) { // statements i++; } It can be somewhat more convenient, and does bring all of the key looping information together (e.g. we can see at a glance that the above loop counts from 0 to 9).

  15. For Loop Details for (expr 1; expr 2; expr 3) { any number of statements } The above is entirely equivalent to: expr 1; while (expr 2) { any number of statements expr 3; } Usually expr 1 initializes some variable, expr 2 (which should produce a bool result) tests this variable, and expr 2 somehow modifies it. As usual, the fundamental C++ “for” only allows one statement in the loop body, and the above is actually the combination of the “for” and a block statement.

  16. For Loop with Declaration The variable used to control a for loop may be declared within the loop as shown below for (int i = 0; i < 10; i++) { any number of statements } // i doesn’t exist here In this case the variable only exists while the loop is being executed, and it cannot be tested or otherwise accessed afterwards. Can be particularily confusing if we’ve already declared a variable with the same name. In this case references inside the loop access the loop variable, and references outside the loop access the other variable. This feature is best avoided unless one really understands what is going on.

  17. A For Example Imagine that we want print out the squares and cubes of all the values between 2 and 20 inclusive, as shown below: Value Square Cube 2 4 8 3 9 27 4 16 64 and so on 20 400 8000 The program does not require any input. The output is to be formatted as shown. This requires a new output manipulator (setw – next slide). See sample program powers.cpp.

  18. Setw setw (integer expression) The setw manipulator affects only the next output operation (unlike the setiosflags and setprecision manipulators) It causes the output to occupy a field of the specified width (if possible – if the specified width is too small, extra positions will be used). By default the output value is right justified in the field and blanks are used as fill characters (both these defaults may be modified). int a = 4095; cout a; // outputs “4095” cout << setw(6) << a; // “ 4095” cout << setw(1) << a; // “4095” cout << setw(8) << a; // “ 4095”

  19. Shortcut Operators var += expression is equivalent to var = (var + expression) var -= expression is equivalent to var = (var – expression) var *= expression is equivalent to var = (var * expression) var /= expression is equivalent to var = (var / expression) Same precedence as =, right associative. Very convenient, especially when dealing with long variable names.

  20. Execute Body Test Condition Is true Is false C++ Do While Loop do { any number of statements } while (boolean expression); Note ; “Post-test” Loop

  21. Prime Number Example (1) Imagine that we want a program which determines whether values are prime numbers (divisible only by themselves and one). We want this program to continue accepting and processing values until –1 is entered. Sample run: Enter a value (-1 to terminate): 46 46 is not prime – divisible by 2 Enter a value (-1 to terminate): 17 17 is prime Enter a value (-1 to terminate) –1 See sample program prime.cpp.

  22. Prime Number Example (2) “First cut” at a solution: cout << “Enter a value (-1 to terminate): “; cin >> number; while (number > 0) { // work out whether the number is prime // and output an appropriate message. // code to do this to be inserted here cout << “Enter a value (-1 to terminate): “; cin >> number; } This is the standard pattern for a “sentinal controlled” loop. Junk values (such as –2, etc.) are treated as being equivalent to -1. This is very reasonable and means that, in writing the processing code, we need not worry about negative values.

  23. Prime Number Example (3) Prime testing algorithm: try dividing by 2, 3, 4, and so on if the number is divisible by the test value then the number isn’t prime – stop if the test value > square root of number then the number is prime - stop Note: if the number is divisible, at least one of the divisors must be less than or equal to the square root of the number. Proof: if both of the divisors were greater than the square root of the number, their product would be greater than the number.

  24. Prime Number Example (4) int number, test; bool still_looking; // our first ever bool variable . . . still_looking = true; // no answer so far test = 2; // our initial test value do { if (test * test > number) { // test > sqrt(number) cout << number << “ is prime” << endl; still_looking = false; } else if ((number % test) == 0) { cout << number << “ is not prime (divisible by “ << test << “)” << endl; still_looking = false; } else { // advance to next test value test++; // still_looking remains true } } while (still_looking); // a boolean expression!!

  25. The Break Statement Format: break; The break statement can be read as “stop looping - exit the loop and pick up with the statement after the loop”. while (. . .) { . . . if (. . .) { break; } . . . } . . . The break doesn’t have to be within an “if” but normally will be – an unconditional break doesn’t make much sense (if we’re always going to break out of it, why have a loop in the first place?). Execution of the break transfers control to the statement after the loop.

  26. Infinite Loops Not a good idea when achieved by accident. Can be useful when combined with some means of exitting the loop (break or return). while (true) { // infinite while loop . . . if (. . .) { break; } . . . } for (;;) { // infinite for loop . . . if (. . .) { break; } . . . }

  27. Sentinal-Control Templates So far: cout << “Enter . . .”; cin >> value; while (value != sentinal_value) { // process value cout << “Enter . . .”; cin >> value; } An alternative (only one cout, one cin): for (;;) { cout << “Enter . . .”; cin >> value; if (value == sentinal_value) { // note change break; } // process value }

  28. Prime Numbers Revisited int number, test; . . . test = 2; // our initial test value for (;;) { if (test * test > number) { // test > sqrt(number) cout << number << “ is prime” << endl; break; } if ((number % test) == 0) { cout << number << “ is not prime (divisible by “ << test << “)” << endl; break; } test++; } // see sample program prime-i.cpp

  29. Break Details In the case of nested loops, a break applies to the immediately enclosing loop. while (. . .) { . . . for (. . .) { . . . if (. . .) { break; // exits the for loop } . . . } . . . if (. . .) { break; // exists the while loop } . . . } Note: within a switch (not covered), breaks apply to the switch, and not to any enclosing loop.

More Related