text
stringlengths
1
7.76k
source
stringlengths
17
81
1.4. Syntax Rules & Pseudocode languages are similar: individual executable commands are written one per line. When a program executes, each command executes one after the other, top-to-bottom. This is known as sequential control flow. A block of code is a section of code that has been logically grouped together. Many l...
ComputerScienceOne_Page_47_Chunk1601
1. Introduction 1.5. Documentation, Comments, and Coding Style Good code is not just functional, it is also beautiful. Good code is organized, easy to read, and well documented. Organization can be achieved by separating code into useful functions and collecting functions into modules or libraries. Good organization me...
ComputerScienceOne_Page_48_Chunk1602
1.5. Documentation, Comments, and Coding Style 11 * front of major portions of code such as a function 12 * to provide documentation 13 * It begins with a forward-slash-star-star 14 */ The last example above is a doc-style comment. It originated with Java, but has since been adopted by many other programming languages....
ComputerScienceOne_Page_49_Chunk1603
2. Basics 2.1. Control Flow The flow of control (or simply control flow) is how a program processes its instructions. Typically, programs operate in a linear or sequential flow of control. Executable statements or instructions in a program are performed one after another. In source code, the order that instructions are wr...
ComputerScienceOne_Page_51_Chunk1604
2. Basics Decision Node (a) Decision Node Control to Perform (b) Control Node Action to Perform (c) Action Node Figure 2.1.: Types of Flowchart Nodes. Control and action nodes are distinguished by color. Control nodes are automated steps while action nodes are steps performed as part of the algorithm being depicted. de...
ComputerScienceOne_Page_52_Chunk1605
2.2. Variables Input PIN Is PIN correct? Eject Card Get amount of withdraw User Input Sufficient Funds? Dispense amount no yes amount no yes Figure 2.2.: Example of a flowchart for a simple ATM process 2.2.1. Naming Rules & Conventions Most programming languages have very specific rules as to what you can use as variable i...
ComputerScienceOne_Page_53_Chunk1606
2. Basics however, using a mixture of lowercase and uppercase letters to refer to the same variable is discouraged: it is difficult to read, inconsistent, and just plain ugly. Beyond the naming rules that languages may enforce, most languages have established naming conventions; a set of guidelines and best-practices for...
ComputerScienceOne_Page_54_Chunk1607
2.2. Variables There are exceptions and special cases to each of these conventions such as when a variable name involves an acronym or a hyphenated word, etc. In such cases sensible extensions or compromises are employed. For example, xmlString or priorityXMLParser (involving the acronym Extensible Markup Language (XML...
ComputerScienceOne_Page_55_Chunk1608
2. Basics the variable apr may be preferred over the longer annualPercentageRate . • Avoid pluralizations, use singular forms – English is not a very consistent language when it comes to rules like pluralizations. For most cases you simply add “s”; for others you add “es” or change the “y” to “i” and add “es”. Some wor...
ComputerScienceOne_Page_56_Chunk1609
2.2. Variables Numeric Types At their most basic, computers are number crunching machines. Thus, the most basic type of variable that can be used in a computer program is a numeric type. There are several numeric types that are supported by various programming languages. The most simple is an integer type which can rep...
ComputerScienceOne_Page_57_Chunk1610
2. Basics as follows. 0b110010000001 = 1 × 211 + 1 × 210 + 0 × 29 + 0 × 28+ 1 × 27 + 0 × 26 + 0 × 25 + 0 × 24+ 0 × 23 + 0 × 22 + 0 × 21 + 1 × 20 = 211 + 210 + 27 + 20 = 2, 048 + 1, 024 + 128 + 1 = 3, 201 Base-10 Binary 0 0b0 1 0b1 2 0b10 3 0b11 4 0b100 5 0b101 6 0b110 7 0b111 8 0b1000 9 0b1001 10 0b1010 11 0b1011 12 0b...
ComputerScienceOne_Page_58_Chunk1611
2.2. Variables Some programming languages allow you to define variables that are unsigned in which the sign bit is not used to indicate positive/negative. With the extra bit we can represent numbers twice as big; using n bits we can represent numbers x in the range 0 ≤x ≤2n −1 Floating point numbers in binary are repres...
ComputerScienceOne_Page_59_Chunk1612
2. Basics Name Bits Exponent Bits Mantissa Bits Significant Digits of Precision Approximate Range Half 16 5 10 ≈3.3 103 ∼104.5 Single 32 8 23 ≈7.2 10−38 ∼1038 Double 64 11 52 ≈15.9 10−308 ∼10308 Quadruple 128 15 112 ≈34.0 10−4931 ∼104931 Table 2.3.: Summary of Floating-point Precisions in the IEEE 754 Standard. Half and...
ComputerScienceOne_Page_60_Chunk1613
2.2. Variables However, there are languages that support arbitrary precision (also called multiprecision) numbers and yet other languages that have many libraries to support “big number” arithmetic. Arbitrary precision is still not infinite: instead, as more digits are needed, more memory is allocated. If you want to co...
ComputerScienceOne_Page_61_Chunk1614
2. Basics Binary Dec Character 0b000 0000 0 \0 Null character 0b000 0001 1 Start of Header 0b000 0010 2 Start of Text 0b000 0011 3 End of Text 0b000 0100 4 End of Transmission 0b000 0101 5 Enquiry 0b000 0110 6 Acknowledgment 0b000 0111 7 \a Bell 0b000 1000 8 \b Backspace 0b000 1001 9 \t Horizontal Tab 0b000 1010 10 \n ...
ComputerScienceOne_Page_62_Chunk1615
2.2. Variables need to be escaped to be defined. For example, though your keyboard has a tab and an enter key, if you wanted to code those characters, you would need to specify them in some way other than using those keys (since typing those keys will affect what you are typing rather than specifying a character). The st...
ComputerScienceOne_Page_63_Chunk1616
2. Basics string types more fully in Chapter 8. Boolean Types A Boolean is another type of variable that is used to hold a truth value, either true or false, of a logical statement. Some programming languages explicitly support a built-in Boolean type while others implicitly support them. For languages that have explic...
ComputerScienceOne_Page_64_Chunk1617
2.2. Variables 2.2.3. Declaring Variables: Dynamic vs. Static Typing In some languages, variables must be declared before they can be referred to or used. When you declare a variable, you not only give it an identifier, but also define its type. For example, you can declare a variable named numberOfStudents and define it ...
ComputerScienceOne_Page_65_Chunk1618
2. Basics 1 { 2 int a; 3 { 4 //this is a new code block inside the outer block 5 int b; 6 //at this point in the code, both a and b are in-scope 7 } 8 //at this point, only a is in-scope, b is out-of-scope 9 } Code Sample 2.1.: Example of variable scoping in C 2.2.4. Scoping The scope of a variable is the section of co...
ComputerScienceOne_Page_66_Chunk1619
2.3. Operators the potential that anything will change the value, greatly increasing the complexity of software testing. To capture the advantages of a global variable while avoiding the disadvantages, it is common to only allow global constants; variables whose values cannot be changed once set. Another argument again...
ComputerScienceOne_Page_67_Chunk1620
2. Basics a = 10; It is important to realize that when this notation is used, it is not an algebraic declaration like a = b which is an algebraic assertion that the variables a and b are equal. An assignment operator is different: it means place the value on the right-hand-side into the variable on the left-hand-side. F...
ComputerScienceOne_Page_68_Chunk1621
2.3. Operators 2.3.2. Numerical Operators Numerical operators allow you to create complex expressions involving either numerical literals and/or numerical variables. For most numerical operators, it doesn’t matter if the operands are integers or floating point numbers. Integers can be added to floating point numbers with...
ComputerScienceOne_Page_69_Chunk1622
2. Basics as a÷b or a/b or a b. In our pseudocode, we’ll generally use a·b and a b, but in programming languages it is difficult to type these symbols. Usually programming languages use * for multiplication and / for division. Similar examples are provided in Algorithm 2.3. 1 a ←10 2 b ←20 3 c ←a · b 4 d ←a b //c has the...
ComputerScienceOne_Page_70_Chunk1623
2.3. Operators Integer Division Recall that in arithmetic, when you divide integers a/b, b might not go into a evenly in which case you get a remainder. For example, 13/5 = 2 with a remainder r = 3. More generally we have that a = qb + r Where a is the dividend, b is the divisor, q is the quotient (the result) and r is...
ComputerScienceOne_Page_71_Chunk1624
2. Basics might result in the string “the answer is 20” being stored in the variable message. Other languages use different symbols to distinguish concatenation and addition. Still yet other languages do not directly support an operator for string concatenation which must instead be done using a function. 2.3.4. Order o...
ComputerScienceOne_Page_72_Chunk1625
2.3. Operators However, many do not. Similarly, the natural logarithm of zero, ln (0) and negative values, ln (−1) is undefined. In either case you could expect a result like “NaN” or “INF.” • Still other operations seem like they should be valid, but because of how numbers are represented in binary, the results are inv...
ComputerScienceOne_Page_73_Chunk1626
2. Basics 2.3.6. Other Operators Many programming languages support other “convenience” operators that allow you to perform common operations using less code. These operators are generally syntactic sugar: the don’t add any functionality. The same operation could be achieved using other operators. However, they do add ...
ComputerScienceOne_Page_74_Chunk1627
2.4. Basic Input/Output 1 int a = 10; 2 a += 5; //adds 5 to a 3 a -= 3; //subtracts 3 from a 4 a *= 2; //multiplies a by 2 5 a /= 4; //divides a by 4 6 7 //you can also use compound assignment operators with variables: 8 int b = 5; 9 a += b; //adds the value stored in b to a 10 a -= b; //subtracts the value stored in b...
ComputerScienceOne_Page_75_Chunk1628
2. Basics 2.4.1. Standard Input & Output The standard input (stdin for short), standard output (stdout) and standard error (stderr) are three standard communication streams that are defined by most computer systems. Though perhaps an over simplification, the keyboard usually serves as a standard input device while the mo...
ComputerScienceOne_Page_76_Chunk1629
2.4. Basic Input/Output Language Standard Output String Output C printf() sprintf() Java System.out.printf() String.format() PHP printf() sprintf() Table 2.5.: printf() -style Methods in Several Languages. Languages support format- ting directly to the Standard Output as well as to strings that can be further used or m...
ComputerScienceOne_Page_77_Chunk1630
2. Basics printf("The value of a = %d, the value of b is %f\n", a, b); Placeholders Format String Print List Figure 2.3.: Elements of a printf() statement in C • %f formats a floating point variable or literal • %c formats a single character variable or literal • %s formats a string variable or literal Misuse of placeho...
ComputerScienceOne_Page_78_Chunk1631
2.4. Basic Input/Output 1 int a = 4567; 2 double b = 3.14159265359; 3 4 printf("a=%d\n", a); 5 printf("a=%2d\n", a); 6 printf("a=%4d\n", a); 7 printf("a=%8d\n", a); 8 9 //by default, prints 6 decimals of precision 10 printf("b=%f\n", b); 11 //the .m modifier is optional: 12 printf("b=%10f\n", b); 13 //the n modifier is...
ComputerScienceOne_Page_79_Chunk1632
2. Basics constantly providing it with input. Most languages and operating systems support non-interactive input from the Command Line Interface (CLI). This is input that is provided at the command line when the program is executed. Input provided from the command line are usually referred to as command line arguments....
ComputerScienceOne_Page_80_Chunk1633
2.5. Debugging Syntax Errors Syntax errors are errors in the usage of a programming language itself. A syntax error can be a failure to adhere to the rules of the language such as misspelling a keyword or forgetting proper “punctuation” (such as missing an ending semicolon). When you have a syntax error, you’re essenti...
ComputerScienceOne_Page_81_Chunk1634
2. Basics A compiler cannot be expected to detect such errors because, by definition, the conditions under which runtime errors occur occur at runtime, not at compile time. One run of a program could execute successfully, while another subsequent run could fail because the system conditions have changed. That doesn’t me...
ComputerScienceOne_Page_82_Chunk1635
2.5. Debugging 2.5.2. Strategies A common beginner’s way of debugging a program is to insert temporary print statements throughout their program to see what values variables have at certain points in an attempt to isolate where an error is occurring. This is an okay strategy for extremely simple programs, but its the “...
ComputerScienceOne_Page_83_Chunk1636
2. Basics 2.6. Examples Let’s apply these concepts by developing several prompt-and-compute style programs. That is, the programs will prompt the user for input, perform some calculations, and then output a result. To write these programs, we’ll use pseudocode, an informal, abstract description of a program/algorithm. ...
ComputerScienceOne_Page_84_Chunk1637
2.7. Exercises 2.6.2. Quadratic Roots A common math exercise is to find the roots of a quadratic equation with coefficients, a, b, c, ax2 + bx + c = 0 using the quadratic formula, x = −b ± √ b2 −4ac 2a Following the same basic outline, we’ll read in the coefficients from the user, compute each of the roots, and output the r...
ComputerScienceOne_Page_85_Chunk1638
2. Basics Exercise 2.2. Write a program to compute the total “cost” C of a loan. That is, the total amount of interest paid over the life of a loan. To compute this value, use the following formula. C = p · i · (1 + i)12n (1 + i)12n −1 ∗12n −p where • p is the starting principle amount • i = r 12 where r is the APR on ...
ComputerScienceOne_Page_86_Chunk1639
2.7. Exercises Exercise 2.7. Write a program to compute the Euclidean Distance between two points, (x1, y2) and (x2, y2) using the formulate: p (x1 −x2)2 + (y1 −y2)2 Exercise 2.8. Write a program that will compute the value of sin(x) using the first 4 terms of the Taylor series: sin(x) ≈x −x3 3! + x5 5! −x7 7! In additi...
ComputerScienceOne_Page_87_Chunk1640
2. Basics Exercise 2.11. Ohm’s Law models the current through a conductor as follows: I = V R where V is the voltage (in volts), R is the resistance (in Ohms) and I is the current (in amps). Write a program that, given two of these values computes the third using Ohm’s Law. The program should work as follows: it prompt...
ComputerScienceOne_Page_88_Chunk1641
2.7. Exercises Sphere Statistics ================= Enter radius r: 2.5 area: 78.539816 volume: 65.449847 Exercise 2.14. Write a program that prompts for the latitude and longitude of two locations (an origin and a destination) on the globe. These numbers are in the range [−180, 180] (negative values correspond to the w...
ComputerScienceOne_Page_89_Chunk1642
2. Basics Enter number of days: 1000 That is 2 years 38 weeks 4 days Exercise 2.16. The derivative of a function f(x) can be estimated using the difference function: f ′(x) ≈f(x + ∆x) −f(x) ∆x That is, this gives us an estimate of the slope of the tangent line at the point x. Write a program that prompts the user for an...
ComputerScienceOne_Page_90_Chunk1643
2.7. Exercises Perpendicular Line ==================== Enter x1: 2.5 Enter y1: 10 Enter x2: 3.5 Enter y2: 11 Original Line: y = 1.0000 x + 7.5000 Perpendicular Line: y = -1.0000 x + 13.5000 Exercise 2.18. Write a program that computes the total for a bill. The program should prompt the user for a sub-total. It should t...
ComputerScienceOne_Page_91_Chunk1644
2. Basics Cost of Investment: $100000.00 Gain of Investment: $120000.00 Return on Investment: 20.00% Exercise 2.20. Write a program to compute the real cost of driving. Gas mileage (in the US) is usually measured in miles per gallon but the real cost should be measured in how much it costs to drive a mile, that is, dol...
ComputerScienceOne_Page_92_Chunk1645
2.7. Exercises simple formula: r = d 180π Write a program to prompt a user for a latitude/longitude of two locations (an origin and a destination) and computes the directional bearing (in degrees) from the origin to the destination. For example, if the user enters: 40.8206, −96.7056 (40.8206◦N, 96.7056◦W) and 41.9483, ...
ComputerScienceOne_Page_93_Chunk1646
2. Basics Your output should be able to handle years, weeks, days, hours, and minutes. So if the user inputs something like 0.9999 and 168, your output should look something like: Traveling at 168.00 hour(s) in your space ship at 99.99% the speed of light, your friends on Earth would experience: 1 year(s) 18 week(s) 3 ...
ComputerScienceOne_Page_94_Chunk1647
2.7. Exercises Exercise 2.24. In sports, the magic number is a number that indicates the combination of the number of games that a leader in a division must win and/or the 2nd place team must lose for the leader to clinch the division. The magic number can be computed using the following formula: G + 1 −WA −LB where G ...
ComputerScienceOne_Page_95_Chunk1648
2. Basics The red-shift equation to determine velocity is given by va = c  1 −λ λr  where • c is the speed of light (299,792.458 km/s) • λ is the actual spectral line of the object (ex: hydrogen is 434nm) • λr is the observed (red-shifted) spectral line and λb is the observed (blue-shifted) spectral line Write a prog...
ComputerScienceOne_Page_96_Chunk1649
2.7. Exercises Write a program that prompts the user to enter D, D0, N, and t1/2 and computes the approximate age of the material, t. For example, if the user were to enter 150, 50, 300, 28.8 (Strontium-90’s half-life) then the program should output something like the following. The sample appears to be 11.953080 years...
ComputerScienceOne_Page_97_Chunk1650
3. Conditionals When writing code, its important to be able to distinguish between one or more situations. Based on some condition being true or false, you may want to perform some action if its true, while performing another, different action if it is false. Alternatively, you may simply want to perform one action if a...
ComputerScienceOne_Page_99_Chunk1651
3. Conditionals 3.1.1. Comparison Operators Suppose we have a variable age representing the age of an individual. Suppose we wish to execute some code if the person is an adult, age ≥18 and a different piece of code if they are not an adult, age < 18. To achieve this, we need to be able to make comparisons between varia...
ComputerScienceOne_Page_100_Chunk1652
3.1. Logical Operators Psuedocode Code Meaning Type < < less than relational > > greater than relational ≤ <= less than or equal to relational ≥ >= greater than or equal to relational = == equal to equality ̸= != not equal to equality Table 3.1.: Comparison Operators Comparisons can also be used with more complex expre...
ComputerScienceOne_Page_101_Chunk1653
3. Conditionals 0 ≤10 and 1 ≤10. However, this is clearly wrong: if x had a value of 20 for example, the first expression would evaluate to false, making the entire expression true, but 20 ̸≤10. The solution is to use logical operators to express the same logic using two comparison operators (see Section 3.1.3). Another...
ComputerScienceOne_Page_102_Chunk1654
3.1. Logical Operators a ¬a false true true false Table 3.2.: Logical Negation, ¬ Operator denote the negation operator1, examples: ¬p, ¬(a > 10), ¬(a ≤b) We will adopt this notation in our pseudocode, however most programming languages use the exclamation mark, ! for the negation operator, similar to its usage in the ...
ComputerScienceOne_Page_103_Chunk1655
3. Conditionals a b a And b false false false false true false true false false true true true Table 3.3.: Logical And Operator The logical And is used to combine logical statements to form more complex logical statements. Recall that we couldn’t directly use two comparison operators to check that a variable falls with...
ComputerScienceOne_Page_104_Chunk1656
3.1. Logical Operators a b a Or b false false false false true true true false true true true true Table 3.4.: Logical Or Operator more complex statements. For example, (age ≥18) Or (year = “senior”) which is true if the individual is aged 18 or older, is a senior, or is both 18 or older and a senior. If the individual...
ComputerScienceOne_Page_105_Chunk1657
3. Conditionals Tautologies and Contradictions Some logical statements have the same meaning regardless of the variables involved. For example, a Or ¬a is always true regardless of the value of a. To see this, suppose that a is true, then the statement becomes a Or ¬a = true Or false which is true. Now suppose that a i...
ComputerScienceOne_Page_106_Chunk1658
3.1. Logical Operators Order Operator 1 ¬ 2 And 3 Or Table 3.5.: Logical Operator Order of Precedence are equivalent to each other; ¬(a Or b) and ¬a And ¬b are also equivalent to each other. Though equivalent, it is generally preferable to write the simpler statement. From one of our previous examples, we could write ¬...
ComputerScienceOne_Page_107_Chunk1659
3. Conditionals In fact, its best practice to write parentheses even if it is not necessary. Writing parentheses is often clearer and easier to read and more importantly communicates intent. By writing a Or (b And c) the intent is clear: we want the And operator to be evaluated first. By not writing the parentheses we l...
ComputerScienceOne_Page_108_Chunk1660
3.2. The If Statement Short circuiting is commonly used to “check” for invalid operations. This is commonly used to prevent invalid operations. For example, consider the following statement: (d ̸= 0 And 1/d > 1) The first operand is checking to see if d is not zero and the second checks to see if its reciprocal is great...
ComputerScienceOne_Page_109_Chunk1661
3. Conditionals just as one reads in English. Moreover, in most programming languages, each statement executes completely before the next statement begins. A visualization of this sequential control flow can be found in the control flow diagram in Figure 3.1(a). However, it is often necessary for a program to “make decis...
ComputerScienceOne_Page_110_Chunk1662
3.3. The If-Else Statement Statement 1 Statement 2 Statement 3 (a) Sequential Flow Chart ⟨condition⟩ Code Block Remaining Program true false (b) If-Statement Flow Chart Figure 3.1.: Control flow diagrams for sequential control flow and an if-statement. In sequential control, statements are executed one after the other as...
ComputerScienceOne_Page_111_Chunk1663
3. Conditionals ⟨condition⟩ Code Block A Code Block B Remaining Program true false Figure 3.2.: An if-else Flow Chart Just as with an if-statement, the keyword “if” is used. In fact, the if-statement is simply just an if-else statement with the else block omitted (equivalently, we could have defined an empty else block,...
ComputerScienceOne_Page_112_Chunk1664
3.4. The If-Else-If Statement 1 if (⟨condition⟩) then 2 Code Block A 3 else 4 Code Block B 5 end Algorithm 3.2: An if-else Statement To illustrate, consider the case in which we have exactly three mutually exclusive possibilities. At a particular university, there are three possible semesters depending on the month. Ja...
ComputerScienceOne_Page_113_Chunk1665
3. Conditionals ⟨condition 1⟩ ⟨condition 2⟩ ⟨condition 3⟩ ... ⟨condition n⟩ Code Block A Code Block B Code Block C ... Code Block N Code Block M Remaining Program if(⟨condition 1⟩) else if(⟨condition 2⟩) else if(⟨condition 3⟩) else if(⟨condition n⟩) else true true true true false false false false false Figure 3.3.: Co...
ComputerScienceOne_Page_114_Chunk1666
3.4. The If-Else-If Statement Algorithm 3.4 and visualized in Figure 3.3. Similar to the if-statement, the else-statement and subsequent code block is optional. If omitted, then it may be possible that none of the code blocks is executed. 1 if (⟨condition 1⟩) then 2 Code Block A 3 else if (⟨condition 2⟩) then 4 Code Bl...
ComputerScienceOne_Page_115_Chunk1667
3. Conditionals specified both lower bounds and upper bounds in our condition. For example, the condition for “intrusive” could have been (decibel > 50) And (decibel ≤70) However, doing this is unnecessary if we order our conditions appropriately and we can potentially write simpler conditions if we remember the fact th...
ComputerScienceOne_Page_116_Chunk1668
3.6. Examples zero. We can then proceed to calculate each of the amounts above. To do this we’ll need an if-statement. We could also use a conditional statement to check to see if the input makes sense: we wouldn’t want a discount amount that is greater than 100%. The full algorithm is presented in Algorithm 3.6. 1 Pro...
ComputerScienceOne_Page_117_Chunk1669
3. Conditionals This approach to programming is known as defensive programming. We are essentially checking the conditions for an invalid operation before performing that operation. In the example above, we simply chose not to perform the operation. Alternatively, we could use an if-else statement to perform alternate ...
ComputerScienceOne_Page_118_Chunk1670
3.6. Examples 3.6.4. Life & Taxes Another example in which there are several cases that have to be considered is computing an income tax liability using marginal tax brackets. Table 3.6 contains the 2014 US Federal tax margins and marginal rates for a married couple filing jointly based on the Adjusted Gross Income (inc...
ComputerScienceOne_Page_119_Chunk1671
3. Conditionals contain our initial tax liability. 1 if income ≤18, 150 then 2 tax ←.10 · income 3 else if income > 18, 150 And income ≤73, 800 then 4 tax ←1, 815 + .15 · (income −18, 150) 5 else if income > 73, 800 And income ≤148, 850 then 6 tax ←10, 162.50 + .25 · (income −73, 800) 7 else if income > 148850 And inco...
ComputerScienceOne_Page_120_Chunk1672
3.7. Exercises 3.7. Exercises Exercise 3.1. Write a program that prompts the user for an x and a y coordinate in the Cartesian plane and prints out a message indicating if the point (x, y) lies on an axis (x or y axis, or both) or what quadrant it lies in (see Figure 3.4). x y Quadrant I Quadrant II Quadrant III Quadra...
ComputerScienceOne_Page_121_Chunk1673
3. Conditionals Gas A: $0.0833 per mile Gas B: $0.0900 per mile Gas A is the better deal. Exercise 3.4. Various substances have different boiling points. A selection of substances and their boiling points can be found in Table 3.7. Write a program that prompts the user for the observed boiling point of a substance in de...
ComputerScienceOne_Page_122_Chunk1674
3.7. Exercises Color Wave length range (nm) Violet 380 – 450 Blue 450 – 475 Indigo 476 – 495 Green 495 – 570 Yellow 570 – 590 Orange 590 – 620 Red 620 - 750 Table 3.9.: Visible Light Spectrum Ranges Write a program that takes an integer corresponding to a wavelength and outputs the corresponding color. If the value lie...
ComputerScienceOne_Page_123_Chunk1675
3. Conditionals Write a program to read in three numbers as the three sides of a triangle. If the three sides do not form a valid triangle, you should indicate so. Otherwise, if valid, your program should output whether or not the triangle is equilateral, isosceles or scalene. (a) Equilateral Triangle (b) Isosceles Tri...
ComputerScienceOne_Page_124_Chunk1676
3.7. Exercises x y (2, 1) (6, 7.5) (4, 5.5) (8.5, 8.25) Figure 3.6.: Intersection of Two Rectangles If the intersection of R1, R2 is a rectangle, R3, your program should output two points (the lower-left and upper-right corners of R3) as well as the area of R3. If the intersection is a line segment, your program should...
ComputerScienceOne_Page_125_Chunk1677
3. Conditionals • Number of minutes in the plan per 30 day period, m • The current day in the 30 day period, d • The total number of minutes used so far u The program should then compute whether the user is over, under, or right on the average daily usage under the plan. It should also inform them of how many minutes a...
ComputerScienceOne_Page_126_Chunk1678
3.7. Exercises 0.9 0.9 9.8 10.0 Center of the room (a) Example 1 0.4 0.4 8.8 10.0 Center of the room (b) Example 2 Figure 3.7.: Examples of Floor Tiling • t - width/length of the tile (all tiles are perfectly square) If we can use whole tiles to perfectly fit the room, then we do so. For example, on the input (10, 10, 1...
ComputerScienceOne_Page_127_Chunk1679
4. Loops Computers are really good at automation. A key aspect of automation is the ability to repeat a process over and over on different pieces of data until some condition is met. For example, if we have a collection of numbers and we want to find their sum we would iterate over each number, adding it to a total, unti...
ComputerScienceOne_Page_129_Chunk1680
4. Loops Initialization: i ←1 Continuation: i ≤10? loop body Iteration: i ←(i + 1) remaining program true repeat false Figure 4.1.: A Typical Loop Flow Chart 96
ComputerScienceOne_Page_130_Chunk1681
4.1. While Loops continues. The iteration statement is intended to update the state of a program to make progress toward the termination condition. If we didn’t make such progress, the loop would continue on forever as the termination condition would never be satisfied. This is known as an infinite loop , and results in ...
ComputerScienceOne_Page_131_Chunk1682
4. Loops performed once and it is done so before the loop code. Then, before the loop code is executed, the continuation condition is checked. Since i = 1 ≤10, the condition evaluates to true and the loop code block is executed. The last line of the code block is the iteration statement, where i is incremented by 1 and...
ComputerScienceOne_Page_132_Chunk1683
4.2. For Loops having to know up front how many times it will execute. Input : A number x, x ≥0 Output : x normalized, k its exponent 1 k ←0 2 while x > 10 do 3 x ←(x/10) 4 k ←(k + 1) 5 end 6 output x, k Algorithm 4.2: Normalizing a Number With a While Loop 4.2. For Loops A for loop is similar to a while loop but allow...
ComputerScienceOne_Page_133_Chunk1684
4. Loops 1 for ( i ←1; i ≤10; i ←(i + 1) ) do 2 Perform some action 3 end Algorithm 4.4: Counter-Controlled For Loop 4.2.1. Example As a more concrete example, consider Algorithm 4.5 in which we do the same iteration (i will take on the values 1, 2, 3, . . . , 10), but in each iteration we add the value of i for that i...
ComputerScienceOne_Page_134_Chunk1685
4.3. Do-While Loops 1 i ←1 2 do 3 Perform some action 4 i ←(i + 1) 5 while i ≤10 Algorithm 4.6: Counter-Controlled Do-While Loop Initialization: i ←1 loop body Iteration: i ←(i + 1) Continuation: i ≤10? remaining program false true Figure 4.2.: A Do-While Loop Flow Chart. The continuation condition is checked after the...
ComputerScienceOne_Page_135_Chunk1686
4. Loops 1 do 2 Read some data 3 isError ←result of reading 4 while isError Algorithm 4.7: Flag-Controlled Do-While Loop that we’ll perform the action before checking to see if it should be performed again. 4.4. Foreach Loops Many languages support a special type of loop for iterating over individual elements in a coll...
ComputerScienceOne_Page_136_Chunk1687
4.5. Other Issues 1 foreach (student s in the class C) do 2 g ←compute a’s grade 3 send a an email informing them of their grade g 4 end Algorithm 4.9: Foreach Loop Computing Grades 4.5. Other Issues 4.5.1. Nested Loops Just as with conditional statements, we can nest loops within loops to perform more complex processe...
ComputerScienceOne_Page_137_Chunk1688
4. Loops termination/continuation condition. Such a loop is referred to as an infinite loop. As an example, suppose we forgot the increment operation from a previous example. 1 sum ←0 2 i ←1 3 while i ≤10 do 4 sum ←(sum + i) 5 end Algorithm 4.11: Infinite Loop In Algorithm 4.11 we never make progress toward the terminati...
ComputerScienceOne_Page_138_Chunk1689
4.5. Other Issues 1 while(days > 365) { 2 if(IsLeapYear(year)) { 3 if(days > 366) { 4 days -= 366; 5 year += 1; 6 } 7 } else { 8 days -= 365; 9 year += 1; 10 } 11 } Code Sample 4.1.: Zune Bug The code worked the vast majority of the time, but this illustrates the need for rigorous testing. 4.5.3. Common Errors When wri...
ComputerScienceOne_Page_139_Chunk1690
4. Loops prone. Finally, you must always ensure that your loops are making progress toward the termina- tion condition. A failure to properly increment a counter can lead to incorrect results or even an infinite loop. 4.5.4. Equivalency of Loops It might not seem obvious at first, but in fact, any type of loop can be re-...
ComputerScienceOne_Page_140_Chunk1691
4.7. Examples 4.7. Examples 4.7.1. For vs While Loop Let’s consider how to write a loop to compute the classic geometric series, 1 1 −x = ∞ X k=0 xk = 1 + x + x2 + x3 + · · · Obviously a computer cannot compute an infinite series as it is required to terminate in a finite number of steps. Thus, we can approach this probl...
ComputerScienceOne_Page_141_Chunk1692
4. Loops This approach will be more straightforward with a while loop since the continuation condition will be more along the lines of “while the estimation is not yet good enough, continue the summation.” This approach will also be easier if we keep track of both a current and a previous value of the summation, then c...
ComputerScienceOne_Page_142_Chunk1693
4.7. Examples Input : n > 1 1 for (i ←2; i ≤√n; i ←(i + 1)) do 2 if i divides n then 3 output composite 4 end 5 end 6 output prime Algorithm 4.14: Determining if a Number is Prime or Composite prime numbers ≤m there are. A key observation is that we’ve already solved part of the problem: determining if a given number i...
ComputerScienceOne_Page_143_Chunk1694
4. Loops Further, banks charge an amount of interest on a loan measured as an Annual Percentage Rate (APR). Given these conditions, the borrower makes monthly payments determined by the following formula. monthlyPayment = iP 1 −(1 + i)−n Where i = apr 12 is the monthly interest rate, and n is the number of terms (in mo...
ComputerScienceOne_Page_144_Chunk1695
4.8. Exercises can’t be $43.871 cents. We’ll need to take care to round properly. This introduces another issue: by rounding the final month’s payment may not match the expected monthly payment (we may over or under pay in the final month). An actual implementation may need to handle the final month’s payment separately w...
ComputerScienceOne_Page_145_Chunk1696
4. Loops 11 21 31 41 51 61 71 81 91 101 12 22 32 42 52 62 72 82 92 102 13 23 33 43 53 63 73 83 93 103 14 24 34 44 54 64 74 84 94 104 15 25 35 45 55 65 75 85 95 105 16 26 36 46 56 66 76 86 96 106 17 27 37 47 57 67 77 87 97 107 18 28 38 48 58 68 78 88 98 108 19 29 39 49 59 69 79 89 99 109 20 30 40 50 60 70 80 90 100 110 ...
ComputerScienceOne_Page_146_Chunk1697
4.8. Exercises Your program will then produce a table detailing the amount of the element that remains after each year until less than 50% of the original amount remains. This amount can be computed using the following formula: r = m × 1 2 (y/H) y is the number of years elapsed, and H is the half-life of the isotope ...
ComputerScienceOne_Page_147_Chunk1698
4. Loops • And the standard deviation, σ = v u u t1 n n X i=1 (xi −µ)2 where n is the number of numbers that was provided. For example, with the numbers, 3.14, 2.71, 42, 3, 13 your output should look something like: Minimum: 2.71 Maximum: 42.00 Mean: 12.77 Variance: 228.77 Standard Deviation: 15.13 Exercise 4.6. The an...
ComputerScienceOne_Page_148_Chunk1699
4.8. Exercises An approximation can be made by taking the first n terms of the series. For n = 4, the approximation is π ≈4 ·  1 −1 3 + 1 5 −1 7  = 2.8952 Write a program that takes n as input and outputs an approximation of π according to the series above. Exercise 4.9. The sine function can be approximated using the...
ComputerScienceOne_Page_149_Chunk1700