Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
|
|
- Stuart Day
- 5 years ago
- Views:
Transcription
1
2 Chapter 3 More Flow of Cotrol Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.
3 Overview 3.1 Usig Boolea Expressios 3.2 Multiway Braches 3.3 More about C++ Loop Statemets 3.4 Desigig Loops Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-3
4 Flow Of Cotrol Flow of cotrol refers to the order i which program statemets are performed We have see the followig ways to specify flow of cotrol if-else-statemets while-statemets do-while-statemets New methods described i this chapter iclude switch-statemets for-statemets Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-4
5 3.1 Usig Boolea Expressios Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.
6 Usig Boolea Expressios A Boolea Expressio is a expressio that is either true or false Boolea expressios are evaluated usig relatioal operatios such as = =, <, ad >= which produce a boolea value ad boolea operatios such as &&,, ad! which also produce a boolea value Type bool allows declaratio of variables that carry the value true or false Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-6
7 Evaluatig Boolea Expressios Boolea expressios are evaluated usig values from the Truth Tables i Display 3.1 For example, if y is 8, the expressio!( ( y < 3) ( y > 7) ) is evaluated i the followig sequece! ( false true )! ( true ) false Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-7
8 Order of Precedece If parethesis are omitted from boolea expressios, the default precedece of operatios is: Perform! operatios first Perform relatioal operatios such as < ext Perform && operatios ext Perform operatios last Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-8
9 Precedece Rules Items i expressios are grouped by precedece rules for arithmetic ad boolea operators Operators with higher precedece are performed first Biary operators with equal precedece are performed left to right Uary operators of equal precedece are performed right to left Display 3.2 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-9
10 Precedece Rule Example The expressio (x+1) > 2 (x + 1) < -3 is equivalet to ( (x + 1) > 2) ( ( x + 1) < -3) Because > ad < have higher precedece tha ad is also equivalet to x + 1 > 2 x + 1 < - 3 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-10
11 Evaluatig x + 1 > 2 x + 1 < - 3 Usig the precedece rules of Display 3.2 First apply the uary Next apply the +'s Now apply the > ad < Fially do the Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-11
12 Short-Circuit Evaluatio Some boolea expressios do ot eed to be completely evaluated if x is egative, the value of the expressio (x >= 0) && ( y > 1) ca be determied by evaluatig oly (x >= 0) C++ uses short-circuit evaluatio If the value of the leftmost sub-expressio determies the fial value of the expressio, the rest of the expressio is ot evaluated Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-12
13 Usig Short-Circuit Evaluatio Short-circuit evaluatio ca be used to prevet ru time errors Cosider this if-statemet if ((kids!= 0) && (pieces / kids >= 2) ) cout << "Each child may have two pieces!"; If the value of kids is zero, short-circuit evaluatio prevets evaluatio of (pieces / 0 >= 2) Divisio by zero causes a ru-time error Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-13
14 Type bool ad Type it C++ ca use itegers as if they were Boolea values Ay o-zero umber (typically 1) is true 0 (zero) is false Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-14
15 Problems with! The expressio (! time > limit ), with limit = 60, is evaluated as (!time) > limit If time is a it with value 36, what is!time? False! Or zero sice it will be compared to a iteger The expressio is further evaluated as 0 > limit false Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-15
16 Correctig the! Problem The itet of the previous expressio was most likely the expressio (! ( time > limit) ) which evaluates as (! ( false) ) true Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-16
17 Avoidig! Just as ot i Eglish ca make thigs ot udifficult to read, the! operator ca make C++ expressios difficult to uderstad Before usig the! operator see if you ca express the same idea more clearly without the! operator Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-17
18 Eumeratio Types (Optioal) A eumeratio type is a type with values defied by a list of costats of type it Example: eum MothLegth{JAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31, DEC_LENGTH = 31}; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-18
19 Default eum Values If umeric values are ot specified, idetifiers are assiged cosecutive values startig with 0 eum Directio { NORTH = 0, SOUTH = 1, EAST = 2, WEST = 3}; is equivalet to eum Directio {NORTH, SOUTH, EAST, WEST}; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-19
20 Eumeratio Values Uless specified, the value assiged a eumeratio costat is 1 more tha the previous costat eum MyEum{ONE = 17, TWO, THREE, FOUR = -3, FIVE}; results i these values ONE = 17, TWO = 18, THREE = 19, FOUR = -3, FIVE = -2 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-20
21 Strog Eums C++11 itroduced a ew versio of eumeratio called strog eums or eum classes that avoids some problems of covetioal eums May ot wat a eum to act like a it Eums are global so you ca t have the same eum value twice Defie a strog eumas follows: Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 1-21
22 Usig Strog Eums To use our strog eums: Days d = Days::Tue; Weather w = Weather::Su; The variables d ad w are ot itegers so we ca t treat them as such. Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 1-22
23 Sectio 3.1 Coclusio Ca you Write a fuctio defiitio for a fuctio amed i_order that takes three argumets of type it? The fuctio returs true if the argumets are i ascedig order; otherwise, it returs false. Determie the value of these Boolea expressios? Assume cout = 0 ad limit = 10 (cout == 0) && (limit < 20)!(cout == 12) (limit < 0) && ((limit /cout) > 7) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-23
24 3.2 Multiway Braches Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.
25 Multiway Braches A brachig mechaism selects oe out of a umber of alterative actios The if-else-statemet is a brachig mechaism Brachig mechaisms ca be a subpart of aother brachig mechaism A if-else-statemet ca iclude aother if-else-statemet as a subpart Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-25
26 Nested Statemets A statemet that is a subpart of aother statemet is a ested statemet Whe writig ested statemets it is ormal to idet each level of estig ideted Example: Display 3.3 if (cout < 10) if ( x < y) cout << x << " is less tha " << y; else cout << y << " is less tha " << x; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-26
27 Nested if-else Statemets Use care i estig if-else-statemets Example: To desig a if-else statemet to war a driver whe fuel is low, but tells the driver to bypass pit stops if the fuel is close to full. Other wise there should be o output. Pseudocode: if fuel gauge is below ¾ the: if fuel gauge is below ¼ the: issue a warig otherwise (gauge > ¾) the: output a statemet sayig do't stop Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-27
28 First Try Nested if's Traslatig the previous pseudocode to C++ could yield (if we are ot careful) if (fuel_gauge_readig < 0.75) if (fuel_gauge_readig < 0.25) cout << "Fuel very low. Cautio!\"; else cout << "Fuel over 3/4. Do't stop ow!\"; This would compile ad ru, but does ot produce the desired results The compiler pairs the "else" with the earest previous "if" Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-28
29 Braces ad Nested Statemets Braces i ested statemets are like parethesis i arithmetic expressios Braces tell the compiler how to group thigs Use braces aroud substatemets Display 3.4 demostrates the use of braces i ested if-else-statemets Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-29
30 Multi-way if-else-statemets A if-else-statemet is a two-way brach Three or four (or more) way braches ca be desiged usig ested if-else-statemets Example: The umber guessig game with the umber stored i variable umber, the guess i variable guess. How do we give hits? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-30
31 Number Guessig The followig ested statemets implemet the hits for our umber guessig game if (guess> umber) cout << "Too high."; else if (guess < umber) cout << "Too low."); else if (guess == umber) cout << "Correct!"; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-31
32 Idetig Nested if-else Notice how the code o the previous slide crept across the page leavig less ad less space Use this alterative for idetig several ested if-else-statemets: if (guess> umber) cout << "Too high."; else if (guess < umber) cout << "Too low."); else if (guess == umber) cout << "Correct!"; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-32
33 The Fial if-else-statemet Whe the coditios tested i a if-else-statemet are mutually exclusive, the fial if-else ca sometimes be omitted. The previous example ca be writte as if (guess> umber) cout << "Too high."; else if (guess < umber) cout << "Too low."); else // (guess == umber) cout << "Correct!"; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-33
34 Nested if-else Sytax A Multiway if-else statemet is writte as if(boolea_expressio_1) Statemet_1 else if ( Boolea_Expressio_2) Statemet_2 else if (Boolea_Expressio_) Statemet _ else Statemet_For_All_Other_Possibilities Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-34
35 Program Example: State Icome Tax Write a program for a state that computes tax accordig to the rate schedule: No tax o first $15,000 of icome 5% tax o each dollar from $15,001 to $25,000 10% tax o each dollar over $25,000 Display 3.5 (1) Display 3.5 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-35
36 Refiig if-else-statemets Notice that the lie else if (( et_icome > && et_icome < = 25000)) ca be replaced with else if (et_icome <= 25000) The computer will ot get to this lie uless it is already determied that et_icome > Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-36
37 The switch-statemet The switch-statemet is a alterative for costructig multi-way braches The example i Display 3.6 determies output based o a letter grade Grades 'A', 'B', ad 'C' each have a brach Grades 'D' ad 'F' use the same brach If a ivalid grade is etered, a default brach is used Display 3.6 (1) Display 3.6 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-37
38 switch-statemet Sytax switch (cotrollig expressio) { case Costat_1: statemet_sequece_1 break; case Costat_2: Statemet_Sequece_2 break;... case Costat_: Statemet_Sequece_ break; default: Default_Statemet_Sequece } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-38
39 The Cotrollig Statemet A switch statemet's cotrollig statemet must retur oe of these types A bool value A eum costat A iteger type A character The value retured is compared to the costat values after each "case" Whe a match is foud, the code for that case is used Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-39
40 The break Statemet The break statemet eds the switch-statemet Omittig the break statemet will cause the code for the ext case to be executed! Omittig a break statemet allows the use of multiple case labels for a sectio of code case 'A': case 'a': cout << "Excellet."; break; Rus the same code for either 'A' or 'a' Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-40
41 The default Statemet If o case label has a costat that matches the cotrollig expressio, the statemets followig the default label are executed If there is o default label, othig happes whe the switch statemet is executed It is a good idea to iclude a default sectio Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-41
42 Switch-statemets ad Meus Nested if-else statemets are more versatile tha a switch statemet Switch-statemets ca make some code more clear A meu is a atural applicatio for a switchstatemet Display 3.7 (1) Display 3.7 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-42
43 Fuctio Calls i Braches Switch ad if-else-statemets allow the use of multiple statemets i a brach Multiple statemets i a brach ca make the switch or if-else-statemet difficult to read Usig fuctio calls (as show i Display 3.7) istead of multiple statemets ca make the switch or if-else-statemet much easier to read Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-43
44 Blocks Each brach of a switch or if-else statemet is a separate sub-task If the actio of a brach is too simple to warrat a fuctio call, use multiple statemets betwee braces A block is a sectio of code eclosed by braces Variables declared withi a block, are local to the block or have the block as their scope. Variable ames declared i the block ca be reused outside the block Display 3.8 (1) Display 3.8 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-44
45 Statemet Blocks A statemet block is a block that is ot a fuctio body or the body of the mai part of a program Statemet blocks ca be ested i other statemet blocks Nestig statemet blocks ca make code difficult to read It is geerally better to create fuctio calls tha to est statemet blocks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-45
46 Scope Rule for Nested Blocks If a sigle idetifier is declared as a variable i each of two blocks, oe withi the other, the these are two differet variables with the same ame Oe of the variables exists oly withi the ier block ad caot be accessed outside the ier block The other variable exists oly i the outer block ad caot be accessed i the ier block Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-46
47 Sectio 3.2 Coclusio Ca you Give the output of this code fragmet? { it x = 1; cout << x << edl; { cout << x << edl; it x = 2; cout << x << edl; } cout << x << edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-47
48 3.3 More About C++ Loop Statemets Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.
49 More About C++ Loop Statemets A loop is a program costructio that repeats a statemet or sequece of statemets a umber of times The body of the loop is the statemet(s) repeated Each repetitio of the loop is a iteratio Loop desig questios: What should the loop body be? How may times should the body be iterated? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-49
50 while ad do-while A importat differece betwee while ad do-while loops: A while loop checks the Boolea expressio at the begiig of the loop A while loop might ever be executed! A do-while loop checks the Boolea expressio at the ed of the loop A do-while loop is always executed at least oce Review while ad do-while sytax i Display 3.9 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-50
51 The Icremet Operator We have used the icremet operator i statemets such as umber++; to icrease the value of umber by oe The icremet operator ca also be used i expressios: it umber = 2; it value_produced = 2 * (umber++); (umber++) first returs the value of umber (2) to be multiplied by 2, the icremets umber to three Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-51
52 umber++ vs ++umber (umber++) returs the curret value of umber, the icremets umber A expressio usig (umber++) will use the value of umber BEFORE it is icremeted (++umber) icremets umber first ad returs the ew value of umber A expressio usig (++umber) will use the value of umber AFTER it is icremeted Number has the same value after either versio! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-52
53 ++ Comparisos it umber = 2; it value_produced = 2 * (umber++); cout << value_produced << " " << umber; displays 4 3 it umber = 2; it value_produced = 2* (++umber); cout << value_produced << " " umber; displays 6 3 Display 3.10 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-53
54 The Decremet Operator The decremet operator (--) decreases the value of the variable by oe it umber = 8; it value_produced = umber--; cout << value_produced << " " << umber; displays 8 7 Replacig "umber--" with "--umber" displays 7 7 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-54
55 The for-statemet A for-statemet (for-loop) is aother loop mechaism i C++ Desiged for commo tasks such as addig umbers i a give rage Is sometimes more coveiet to use tha a while loop Does ot do aythig a while loop caot do Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-55
56 for/while Loop Compariso sum = 0; = 1; while( <= 10) // add the umbers 1-10 { sum = sum + ; ++; } sum = 0; for ( = 1; <= 10; ++) //add the umbers 1-10 sum = sum + ; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-56
57 For Loop Dissectio The for loop uses the same compoets as the while loop i a more compact form for ( = 1; <= 10; ++) Iitializatio Actio Update Actio Boolea Expressio Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-57
58 for Loop Alterative A for loop ca also iclude a variable declaratio i the iitializatio actio for (it = 1; < = 10; ++) This lie meas Create a variable,, of type it ad iitialize it with 1 Cotiue to iterate the body as log as <= 10 Icremet by oe after each iteratio For-loop sytax ad while loop compariso are foud i Display 3.11 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-58
59 for-loop Details Iitializatio ad update actios of for-loops ofte cotai more complex expressios Here are some samples for ( = 1; < = 10; = + 2) for( = 0 ; > -100 ; = -7) for(double x = pow(y,3.0); x > 2.0; x = sqrt(x) ) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-59
60 The for-loop Body The body of a for-loop ca be A sigle statemet A compoud statemet eclosed i braces Example: Display 3.13 for(it umber = 1; umber >= 0; umber--) { // loop body statemets } shows the sytax for a for-loop with a multi-statemet body Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-60
61 The Empty Statemet A semicolo creates a C++ statemet Placig a semicolo after x++ creates the statemet x++; Placig a semicolo after othig creates a empty statemet that compiles but does othig cout << "Hello" << edl; ; cout << "Good Bye"<< edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-61
62 Extra Semicolo Placig a semicolo after the paretheses of a for loop creates a empty statemet as the body of the loop Example: for(it cout = 1; cout <= 10; cout++); cout << "Hello\"; prits oe "Hello", but ot as part of the loop! The empty statemet is the body of the loop cout << "Hello\"; is ot part of the loop body! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-62
63 Local Variable Stadard ANSI C++ stadard requires that a variable declared i the for-loop iitializatio sectio be local to the block of the for-loop Fid out how your compiler treats these variables! If you wat your code to be portable, do ot deped o all compilers to treat these variables as local to the for-loop! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-63
64 Which Loop To Use? Choose the type of loop late i the desig process First desig the loop usig pseudocode Traslate the pseudocode ito C++ The traslatio geerally makes the choice of a appropriate loop clear While-loops are used for all other loops whe there might be occassios whe the loop should ot ru Do-while loops are used for all other loops whe the loop must always ru at least oce Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-64
65 Choosig a for-loop for-loops are typically selected whe doig umeric calculatios, especially whe usig a variable chaged by equal amouts each time the loop iterates Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-65
66 Choosig a while-loop A while-loop is typically used Whe a for-loop is ot appropriate Whe there are circumstaces for which the loop body should ot be executed at all Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-66
67 Choosig a do-while Loop A do-while-loop is typically used Whe a for-loop is ot appropriate Whe the loop body must be executed at least oce Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-67
68 The break-statemet There are times to exit a loop before it eds If the loop checks for ivalid iput that would rui a calculatio, it is ofte best to ed the loop The break-statemet ca be used to exit a loop before ormal termiatio Be careful with ested loops! Usig break oly exits the loop i which the break-statemet occurs Display 3.14 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-68
69 Sectio 3.3 Coclusio Ca you Determie the output of the followig? for(it cout = 1; cout < 5; cout++) cout << (2 * cout) << " " ; Determie which type of loop is likely to be best for Summig a series such as 1/2 + 1/3 + 1/ /10? Readig a list of exam scores for oe studet? Testig a fuctio to see how it performs with differet values of its argumets Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-69
70 3.4 Desigig Loops Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.
71 Desigig Loops Desigig a loop ivolves desigig The body of the loop The iitializig statemets The coditios for edig the loop Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-71
72 Sums ad Products A commo task is readig a list of umbers ad computig the sum Pseudocode for this task might be: sum = 0; repeat the followig this_may times ci >> ext; sum = sum + ext; ed of loop This pseudocode ca be implemeted with a for-loop as show o the ext slide Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-72
73 for-loop for a sum The pseudocode from the previous slide is implemeted as it sum = 0; for(it cout=1; cout <= this_may; cout++) { ci >> ext; sum = sum + ext; } sum must be iitialized prior to the loop body! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-73
74 Repeat "this may times" Pseudocode cotaiig the lie repeat the followig "this may times" is ofte implemeted with a for-loop A for-loop is geerally the choice whe there is a predetermied umber of iteratios Example: for(it cout = 1; cout <= this_may; cout++) Loop_body Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-74
75 for-loop For a Product Formig a product is very similar to the sum example see earlier it product = 1; for(it cout=1; cout <= this_may; cout++) { ci >> ext; product = product * ext; } product must be iitialized prior to the loop body Notice that product is iitialized to 1, ot 0! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-75
76 Edig a Loop The are four commo methods to termiate a iput loop List headed by size Whe we ca determie the size of the list beforehad Ask before iteratig Ask if the user wats to cotiue before each iteratio List eded with a setiel value Usig a particular value to sigal the ed of the list Ruig out of iput Usig the eof fuctio to idicate the ed of a file Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-76
77 List Headed By Size The for-loops we have see provide a atural implemetatio of the list headed by size method of edig a loop Example: it items; cout << "How may items i the list?"; ci >> items; for(it cout = 1; cout <= items; cout++) { it umber; cout << "Eter umber " << cout; ci >> umber; cout << edl; // statemets to process the umber } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-77
78 Ask Before Iteratig A while loop is used here to implemet the ask before iteratig method to ed a loop sum = 0; cout << "Are there umbers i the list (Y/N)?"; char as; ci >> as; while (( as = 'Y') (as = 'y')) { //statemets to read ad process the umber cout << "Are there more umbers(y/n)? "; ci >> as; } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-78
79 List Eded With a Setiel Value A while loop is typically used to ed a loop usig the list eded with a setiel value method cout << "Eter a list of oegative itegers.\" << "Place a egative iteger after the list.\"; sum = 0; ci >> umber; while (umber > 0) { //statemets to process the umber ci >> umber; } Notice that the setiel value is read, but ot processed Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-79
80 Ruig Out of Iput The while loop is typically used to implemet the ruig out of iput method of edig a loop ifstream ifile; ifile.ope("data.dat"); while (! ifile.eof( ) ) { // read ad process items from the file // File I/O covered i Chapter 6 } ifile.close( ); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-80
81 Geeral Methods To Cotrol Loops Three geeral methods to cotrol ay loop Cout cotrolled loops Ask before iteratig Exit o flag coditio Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-81
82 Cout Cotrolled Loops Cout cotrolled loops are loops that determie the umber of iteratios before the loop begis The list headed by size is a example of a cout cotrolled loop for iput Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-82
83 Exit o Flag Coditio Loops ca be eded whe a particular flag coditio exists A variable that chages value to idicate that some evet has take place is a flag Examples of exit o a flag coditio for iput List eded with a setiel value Ruig out of iput Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-83
84 Exit o Flag Cautio Cosider this loop to idetify a studet with a grade of 90 or better it = 1; grade = compute_grade(); while (grade < 90) { ++; grade = compute_grade(); } cout << "Studet umber " << << " has a score of " << grade << edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-84
85 The Problem The loop o the previous slide might ot stop at the ed of the list of studets if o studet has a grade of 90 or higher It is a good idea to use a secod flag to esure that there are still studets to cosider The code o the followig slide shows a better solutio Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-85
86 The Exit O Flag Solutio This code solves the problem of havig o studet grade at 90 or higher it =1; grade = compute_grade(); while (( grade < 90) && ( < umber_of_studets)) { // same as before } if (grade > 90) // same output as before else cout << "No studet has a high score."; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-86
87 Nested Loops The body of a loop may cotai ay kid of statemet, icludig aother loop Whe loops are ested, all iteratios of the ier loop are executed for each iteratio of the outer loop Give serious cosideratio to makig the ier loop a fuctio call to make it easier to read your program Display 3.15 show two versios of a program with ested loops Display 3.15 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-87
88 Debuggig Loops Commo errors ivolvig loops iclude Off-by-oe errors i which the loop executes oe too may or oe too few times Ifiite loops usually result from a mistake i the Boolea expressio that cotrols the loop Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-88
89 Fixig Off By Oe Errors Check your compariso: should it be < or <=? Check that the iitializatio uses the correct value Does the loop hadle the zero iteratios case? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-89
90 Fixig Ifiite Loops Check the directio of iequalities: < or >? Test for < or > rather tha equality (==) Remember that doubles are really oly approximatios Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-90
91 More Loop Debuggig Tips Be sure that the mistake is really i the loop Trace the variable to observe how the variable chages Tracig a variable is watchig its value chage durig executio May systems iclude utilities to help with this cout statemets ca be used to trace a value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-91
92 Debuggig Example The followig code is supposed to coclude with the variable product cotaiig the product of the umbers 2 through 5 it ext = 2, product = 1; while (ext < 5) { ext++; product = product * ext; } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-92
93 Tracig Variables Add temporary cout statemets to trace variables it ext = 2, product = 1; while (ext < 5) { ext++; product = product * ext; cout << "ext = " << ext << "product = " << product << edl; } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-93
94 First Fix The cout statemets added to the loop show us that the loop ever multiplied by 2 Solve the problem by movig the statemet ext++ it ext = 2, product = 1; while (ext < 5) { product = product * ext; ext++; } cout << "ext = " << ext << "product = " << product << edl; There is still a problem! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-94
95 Secod Fix Re-testig the loop shows us that ow the loop ever multiplies by 5 The fix is to use <= istead of < i our compariso it ext = 2, product = 1; while (ext <= 5) { product = product * ext; ext++; } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-95
96 Loop Testig Guidelies Every time a program is chaged, it must be retested Chagig oe part may require a chage to aother Every loop should at least be tested usig iput to cause: Zero iteratios of the loop body Oe iteratio of the loop body Oe less tha the maximum umber of iteratios The maximum umber of iteratos Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-96
97 Startig Over Sometimes it is more efficiet to throw out a buggy program ad start over The ew program will be easier to read The ew program is less likely to be as buggy You may develop a workig program faster tha if you repair the bad code The lessos leared i the buggy code will help you desig a better program faster Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-97
98 Chapter 3.4 Coclusio Ca you Describe how to trace a variable? List possible solutios to a off-by-oe error? Determie the umber of fece posts eeded for a 100 meter log fece? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-98
99 Chapter 3 -- Ed Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-99
100 Display 3.1 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-100
101 Display 3.2 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-101
102 Display 3.3 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-102
103 Display 3.4 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-103
104 Display 3.5 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-104
105 Display 3.5 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-105
106 Display 3.6 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-106
107 Display 3.6 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-107
108 Display 3.7 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-108
109 Display 3.7 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-109
110 Display 3.8 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-110
111 Display 3.8 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-111
112 Display 3.9 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-112
113 Display 3.10 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-113
114 Display 3.11 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-114
115 Display 3.12 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-115
116 Display 3.13 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-116
117 Display 3.14 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-117
118 Display 3.15 Back Next //DISPLAY 3.15 Explicitly Nested Loops //Determies the total umber of gree-ecked vulture eggs //couted by all coservatioists i the coservatio district. #iclude <iostream> usig amespace std; it mai() { cout << "This program tallies coservatioist reports\" << "o the gree-ecked vulture.\" << "Each coservatioist's report cosists of\" << "a list of umbers. Each umber is the cout of\" << "the eggs observed i oe " << "gree-ecked vulture est.\" << "This program the tallies " << "the total umber of eggs.\"; it umber_of_reports; cout << "How may coservatioist reports are there? "; ci >> umber_of_reports; it grad_total = 0, subtotal, cout; for (cout = 1; cout <= umber_of_reports; cout++) { cout << edl << "Eter the report of " << "coservatioist umber " << cout << edl; } cout << "Eter the umber of eggs i each est.\" << "Place a egative iteger at the ed of your list.\"; subtotal = 0; it ext; ci >> ext; while (ext >=0) { subtotal = subtotal + ext; ci >> ext; } cout << "Total egg cout for coservatioist " << " umber " << cout << " is " << subtotal << edl; grad_total = grad_total + subtotal; } cout << edl << "Total egg cout for all reports = " << grad_total << edl; retur 0; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 3-118
Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4
More informationChapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig
More informationChapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 2 C++ Basics Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 2.1 Variables ad Assigmets 2.2 Iput ad Output 2.3 Data Types ad Expressios 2.4 Simple Flow of Cotrol 2.5 Program
More informationCS 11 C track: lecture 1
CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material
More informationChapter 3. More Flow of Control
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-2 Flow Of Control Flow of control refers to the
More informationChapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4
More information. Written in factored form it is easy to see that the roots are 2, 2, i,
CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or
More informationChapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.
More informationChapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..
More informationChapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3
More informationCSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)
CSC165H1, Witer 018 Learig Objectives By the ed of this worksheet, you will: Aalyse the ruig time of fuctios cotaiig ested loops. 1. Nested loop variatios. Each of the followig fuctios takes as iput a
More informationChapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,
More informationAnalysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis
Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems
More informationChapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs
More informationChapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig
More informationChapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationRecursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames
Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationAbstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:
Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to
More informationn Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis
Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig
More informationn Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.
Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,
More informationCMPT 125 Assignment 2 Solutions
CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address
More informationComputers and Scientific Thinking
Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput
More informationPseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Pseudocode ( 1.1) High-level descriptio of a algorithm More structured
More informationOutline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis
Outlie ad Readig Aalysis of Algorithms Iput Algorithm Output Ruig time ( 3.) Pseudo-code ( 3.2) Coutig primitive operatios ( 3.3-3.) Asymptotic otatio ( 3.6) Asymptotic aalysis ( 3.7) Case study Aalysis
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists
More informationBehavioral Modeling in Verilog
Behavioral Modelig i Verilog COE 202 Digital Logic Desig Dr. Muhamed Mudawar Kig Fahd Uiversity of Petroleum ad Mierals Presetatio Outlie Itroductio to Dataflow ad Behavioral Modelig Verilog Operators
More informationCSC 220: Computer Organization Unit 11 Basic Computer Organization and Design
College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:
More information9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence
_9.qxd // : AM Page Chapter 9 Sequeces, Series, ad Probability 9. Sequeces ad Series What you should lear Use sequece otatio to write the terms of sequeces. Use factorial otatio. Use summatio otatio to
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13
CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis
More informationRunning Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects. The
More informationRunning Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time ( 3.1) Aalysis of Algorithms Iput Algorithm Output A algorithm is a step- by- step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects.
More informationAnalysis of Algorithms
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Ruig Time Most algorithms trasform iput objects ito output objects. The
More informationHomework 1 Solutions MA 522 Fall 2017
Homework 1 Solutios MA 5 Fall 017 1. Cosider the searchig problem: Iput A sequece of umbers A = [a 1,..., a ] ad a value v. Output A idex i such that v = A[i] or the special value NIL if v does ot appear
More informationHow do we evaluate algorithms?
F2 Readig referece: chapter 2 + slides Algorithm complexity Big O ad big Ω To calculate ruig time Aalysis of recursive Algorithms Next time: Litterature: slides mostly The first Algorithm desig methods:
More informationChapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 6 I/O Streams as a Itroductio to Objects ad Classes Overview 6.1 Streams ad Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams ad Basic File I/O I/O Streams I/O refers
More informationComputer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.
Computer Sciece Foudatio Exam August, 005 Computer Sciece Sectio A No Calculators! Name: SSN: KEY Solutios ad Gradig Criteria Score: 50 I this sectio of the exam, there are four (4) problems. You must
More informationData Structures and Algorithms. Analysis of Algorithms
Data Structures ad Algorithms Aalysis of Algorithms Outlie Ruig time Pseudo-code Big-oh otatio Big-theta otatio Big-omega otatio Asymptotic algorithm aalysis Aalysis of Algorithms Iput Algorithm Output
More informationExceptions. Your computer takes exception. The Exception Class. Causes of Exceptions
Your computer takes exceptio s s are errors i the logic of a program (ru-time errors). Examples: i thread mai java.io.filenotfoud: studet.txt (The system caot fid the file specified.) i thread mai java.lag.nullpoiter:
More informationWhat are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs
What are we goig to lear? CSC316-003 Data Structures Aalysis of Algorithms Computer Sciece North Carolia State Uiversity Need to say that some algorithms are better tha others Criteria for evaluatio Structure
More informationCS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June
CS 1313 010: Programmig for No-Majors, Summer 2007 Programmig Project #3: Two Little Calculatios Due by 12:00pm (oo) Wedesday Jue 27 2007 This third assigmet will give you experiece writig programs that
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19
CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.
More informationIt just came to me that I 8.2 GRAPHS AND CONVERGENCE
44 Chapter 8 Discrete Mathematics: Fuctios o the Set of Natural Numbers (a) Take several odd, positive itegers for a ad write out eough terms of the 3N sequece to reach a repeatig loop (b) Show that ot
More informationCopyright 2016 Ramez Elmasri and Shamkant B. Navathe
Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 18 Strategies for Query Processig Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio DBMS techiques to process a query Scaer idetifies
More informationCh 9.3 Geometric Sequences and Series Lessons
Ch 9.3 Geometric Sequeces ad Series Lessos SKILLS OBJECTIVES Recogize a geometric sequece. Fid the geeral, th term of a geometric sequece. Evaluate a fiite geometric series. Evaluate a ifiite geometric
More informationJava Expressions & Flow Control
Java Expressios & Flow Cotrol Rui Moreira Expressio Separators:. [ ] ( ), ; Dot used as decimal separator or to access attributes ad methods double d = 2.6; Poto poto = ew Poto(2, 3); it i = poto.x; it
More informationLecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming
Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis
More informationArithmetic Sequences
. Arithmetic Sequeces COMMON CORE Learig Stadards HSF-IF.A. HSF-BF.A.1a HSF-BF.A. HSF-LE.A. Essetial Questio How ca you use a arithmetic sequece to describe a patter? A arithmetic sequece is a ordered
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig
More informationSolution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:
CS 604 Data Structures Midterm Sprig, 00 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Istructios: Prit your ame i the space provided below. This examiatio is closed book ad closed
More informationElementary Educational Computer
Chapter 5 Elemetary Educatioal Computer. Geeral structure of the Elemetary Educatioal Computer (EEC) The EEC coforms to the 5 uits structure defied by vo Neuma's model (.) All uits are preseted i a simplified
More informationOne advantage that SONAR has over any other music-sequencing product I ve worked
*gajedra* D:/Thomso_Learig_Projects/Garrigus_163132/z_productio/z_3B2_3D_files/Garrigus_163132_ch17.3d, 14/11/08/16:26:39, 16:26, page: 647 17 CAL 101 Oe advatage that SONAR has over ay other music-sequecig
More informationEE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering
EE 4363 1 Uiversity of Miesota Midterm Exam #1 Prof. Matthew O'Keefe TA: Eric Seppae Departmet of Electrical ad Computer Egieerig Uiversity of Miesota Twi Cities Campus EE 4363 Itroductio to Microprocessors
More informationFrom last week. Lecture 5. Outline. Principles of programming languages
Priciples of programmig laguages From last week Lecture 5 http://few.vu.l/~silvis/ppl/2007 Natalia Silvis-Cividjia e-mail: silvis@few.vu.l ML has o assigmet. Explai how to access a old bidig? Is & for
More informationCOSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1
COSC 1P03 Ch 7 Recursio Itroductio to Data Structures 8.1 COSC 1P03 Recursio Recursio I Mathematics factorial Fiboacci umbers defie ifiite set with fiite defiitio I Computer Sciece sytax rules fiite defiitio,
More informationStructuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software
Structurig Redudacy for Fault Tolerace CSE 598D: Fault Tolerat Software What do we wat to achieve? Versios Damage Assessmet Versio 1 Error Detectio Iputs Versio 2 Voter Outputs State Restoratio Cotiued
More informationBasic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.
5-23 The course that gives CM its Zip Memory Maagemet II: Dyamic Storage Allocatio Mar 6, 2000 Topics Segregated lists Buddy system Garbage collectio Mark ad Sweep Copyig eferece coutig Basic allocator
More informationCopyright 2016 Ramez Elmasri and Shamkant B. Navathe
Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 19 Query Optimizatio Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio Query optimizatio Coducted by a query optimizer i a DBMS Goal:
More informationCS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions
CS 111: Program Desig I Lecture # 7: First Loop, Web Crawler, Fuctios Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago September 18, 2018 What will this prit? x = 5 if x == 3: prit("hi!")
More information10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output
File class i Java File Iput ad Output TOPICS File Iput Exceptio Hadlig File Output Programmers refer to iput/output as "I/O". The File class represets files as objects. The class is defied i the java.io
More informationRecursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:
Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical
More informationAlgorithm. Counting Sort Analysis of Algorithms
Algorithm Coutig Sort Aalysis of Algorithms Assumptios: records Coutig sort Each record cotais keys ad data All keys are i the rage of 1 to k Space The usorted list is stored i A, the sorted list will
More information1.2 Binomial Coefficients and Subsets
1.2. BINOMIAL COEFFICIENTS AND SUBSETS 13 1.2 Biomial Coefficiets ad Subsets 1.2-1 The loop below is part of a program to determie the umber of triagles formed by poits i the plae. for i =1 to for j =
More informationData diverse software fault tolerance techniques
Data diverse software fault tolerace techiques Complemets desig diversity by compesatig for desig diversity s s limitatios Ivolves obtaiig a related set of poits i the program data space, executig the
More informationLecture 1: Introduction and Strassen s Algorithm
5-750: Graduate Algorithms Jauary 7, 08 Lecture : Itroductio ad Strasse s Algorithm Lecturer: Gary Miller Scribe: Robert Parker Itroductio Machie models I this class, we will primarily use the Radom Access
More informationCOMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design
COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Chapter The Processor Part A path Desig Itroductio CPU performace factors Istructio cout Determied by ISA ad compiler. CPI ad
More informationn n B. How many subsets of C are there of cardinality n. We are selecting elements for such a
4. [10] Usig a combiatorial argumet, prove that for 1: = 0 = Let A ad B be disjoit sets of cardiality each ad C = A B. How may subsets of C are there of cardiality. We are selectig elemets for such a subset
More informationClasses and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1
Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1 The simplest
More informationthe beginning of the program in order for it to work correctly. Similarly, a Confirm
I our sytax, a Assume statemet will be used to record what must be true at the begiig of the program i order for it to work correctly. Similarly, a Cofirm statemet is used to record what should be true
More informationCOP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall 2016
More informationExamples and Applications of Binary Search
Toy Gog ITEE Uiersity of Queeslad I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We
More informationThreads and Concurrency in Java: Part 1
Cocurrecy Threads ad Cocurrecy i Java: Part 1 What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.
More informationAPPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS
APPLICATION NOTE PACE175AE BUILT-IN UNCTIONS About This Note This applicatio brief is iteded to explai ad demostrate the use of the special fuctios that are built ito the PACE175AE processor. These powerful
More informationSolutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer
Departmet of Computer ciece Columbia Uiversity olutios to Fial COM W45 Programmig Laguages ad Traslators Moday, May 4, 2009 4:0-5:25pm, 309 Havemeyer Closed book, o aids. Do questios 5. Each questio is
More information6.854J / J Advanced Algorithms Fall 2008
MIT OpeCourseWare http://ocw.mit.edu 6.854J / 18.415J Advaced Algorithms Fall 2008 For iformatio about citig these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 18.415/6.854 Advaced Algorithms
More informationThreads and Concurrency in Java: Part 1
Threads ad Cocurrecy i Java: Part 1 1 Cocurrecy What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.
More informationAnalysis of Algorithms
Presetatio for use with the textbook, Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Aalysis of Algorithms Iput 2015 Goodrich ad Tamassia Algorithm Aalysis of Algorithms
More informationPattern Recognition Systems Lab 1 Least Mean Squares
Patter Recogitio Systems Lab 1 Least Mea Squares 1. Objectives This laboratory work itroduces the OpeCV-based framework used throughout the course. I this assigmet a lie is fitted to a set of poits usig
More informationGE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III
GE2112 - FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III PROBLEM SOLVING AND OFFICE APPLICATION SOFTWARE Plaig the Computer Program Purpose Algorithm Flow Charts Pseudocode -Applicatio Software Packages-
More informationThe Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004
8 Programs ad data This publicatio forms part of a Ope Uiversity course M150 Data, Computig ad Iformatio. Details of this ad other Ope Uiversity courses ca be obtaied from the Course Iformatio ad Advice
More informationCode Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013
Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of
More informationUniversity of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures
Uiversity of Waterloo Departmet of Electrical ad Computer Egieerig ECE 250 Algorithms ad Data Structures Midterm Examiatio ( pages) Istructor: Douglas Harder February 7, 2004 7:30-9:00 Name (last, first)
More informationCHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs
CHAPTER IV: GRAPH THEORY Sectio : Itroductio to Graphs Sice this class is called Number-Theoretic ad Discrete Structures, it would be a crime to oly focus o umber theory regardless how woderful those topics
More informationPolynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0
Polyomial Fuctios ad Models 1 Learig Objectives 1. Idetify polyomial fuctios ad their degree 2. Graph polyomial fuctios usig trasformatios 3. Idetify the real zeros of a polyomial fuctio ad their multiplicity
More informationThe Magma Database file formats
The Magma Database file formats Adrew Gaylard, Bret Pikey, ad Mart-Mari Breedt Johaesburg, South Africa 15th May 2006 1 Summary Magma is a ope-source object database created by Chris Muller, of Kasas City,
More informationcondition w i B i S maximum u i
ecture 10 Dyamic Programmig 10.1 Kapsack Problem November 1, 2004 ecturer: Kamal Jai Notes: Tobias Holgers We are give a set of items U = {a 1, a 2,..., a }. Each item has a weight w i Z + ad a utility
More informationThreads and Concurrency in Java: Part 2
Threads ad Cocurrecy i Java: Part 2 1 Waitig Sychroized methods itroduce oe kid of coordiatio betwee threads. Sometimes we eed a thread to wait util a specific coditio has arise. 2003--09 T. S. Norvell
More informationCS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts
CS 111 Gree: Program Desig I Lecture 27: Speed (cot.); partig thoughts By Nascarkig - Ow work, CC BY-SA 4.0, https://commos.wikimedia.org/w/idex.php?curid=38671041 Robert H. Sloa (CS) & Rachel Poretsky
More informationOnes Assignment Method for Solving Traveling Salesman Problem
Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:
More informationChapter 4 The Datapath
The Ageda Chapter 4 The Datapath Based o slides McGraw-Hill Additioal material 24/25/26 Lewis/Marti Additioal material 28 Roth Additioal material 2 Taylor Additioal material 2 Farmer Tae the elemets that
More informationCIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)
CIS 11 Data Structures ad Algorithms with Java Fall 017 Big-Oh Notatio Tuesday, September 5 (Make-up Friday, September 8) Learig Goals Review Big-Oh ad lear big/small omega/theta otatios Practice solvig
More informationTask scenarios Outline. Scenarios in Knowledge Extraction. Proposed Framework for Scenario to Design Diagram Transformation
6-0-0 Kowledge Trasformatio from Task Scearios to View-based Desig Diagrams Nima Dezhkam Kamra Sartipi {dezhka, sartipi}@mcmaster.ca Departmet of Computig ad Software McMaster Uiversity CANADA SEKE 08
More informationGetting Started. Getting Started - 1
Gettig Started Gettig Started - 1 Issue 1 Overview of Gettig Started Overview of Gettig Started This sectio explais the basic operatios of the AUDIX system. It describes how to: Log i ad log out of the
More informationHash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.
Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Hash Tables xkcd. http://xkcd.com/221/. Radom Number. Used with permissio uder Creative
More informationNTH, GEOMETRIC, AND TELESCOPING TEST
NTH, GEOMETRIC, AND TELESCOPING TEST Sectio 9. Calculus BC AP/Dual, Revised 08 viet.dag@humbleisd.et /4/08 0:0 PM 9.: th, Geometric, ad Telescopig Test SUMMARY OF TESTS FOR SERIES Lookig at the first few
More informationLecture 6. Lecturer: Ronitt Rubinfeld Scribes: Chen Ziv, Eliav Buchnik, Ophir Arie, Jonathan Gradstein
068.670 Subliear Time Algorithms November, 0 Lecture 6 Lecturer: Roitt Rubifeld Scribes: Che Ziv, Eliav Buchik, Ophir Arie, Joatha Gradstei Lesso overview. Usig the oracle reductio framework for approximatig
More informationA graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))
ca see that time required to search/sort grows with size of We How do space/time eeds of program grow with iput size? iput. time: cout umber of operatios as fuctio of iput Executio size operatio Assigmet:
More informationBig-O Analysis. Asymptotics
Big-O Aalysis 1 Defiitio: Suppose that f() ad g() are oegative fuctios of. The we say that f() is O(g()) provided that there are costats C > 0 ad N > 0 such that for all > N, f() Cg(). Big-O expresses
More informationLocation Steps and Paths
Locatio Steps ad Paths 3 INTHIS CHAPTER Uderstadig Locatio Steps ad Paths How do locatio paths work? We took a look at locatio paths i the overview i Chapter 1, where we saw that locatio paths look much
More information