text
stringlengths
1
7.76k
source
stringlengths
17
81
12.1. Searching comparisons (see Table 12.1). Thus, binary search performs a logarithmic number of comparisons in the worst case. As we will see, this is exponentially better than linear search. Iteration Array Size Comparisons 1 n 2 1 2 n 4 1 3 n 8 1 4 n 16 1 ... ... ... k n 2k 1 ... ... ... log2 (n) 1 1 log2 (n) + 1 ...
ComputerScienceOne_Page_253_Chunk1801
12. Searching & Sorting input size, n →2n, we would expect the number of comparisons performed by linear search to also double. However, if we double the input size for binary search, we get the following. log2 (2n) = log2 (2) + log (n) = log (n) + 1 That is, only a single additional comparison is necessary to search a...
ComputerScienceOne_Page_254_Chunk1802
12.2. Sorting collection, we can determine whether a < b, a = b or a > b. If such a determination cannot be made, then sorting is impossible. Again, we can consider variations on this problem. We may want our collection to be sorted in descending order instead of ascending.6 We may also want the collection itself to be...
ComputerScienceOne_Page_255_Chunk1803
12. Searching & Sorting Sort in Figure 12.5. Input : A collection A = {a1, . . . , an} Output : An array A′ containing all elements of A in nondecreasing order 1 for i = 1, . . . , (n −1) do 2 amin ←ai 3 for j = (i + 1), . . . , n do 4 if amin > aj then 5 min ←aj 6 end 7 end 8 swap amin and ai 9 end Algorithm 12.4: Sel...
ComputerScienceOne_Page_256_Chunk1804
12.2. Sorting 42 4 9 4 102 34 12 2 0 swap 0 4 9 4 102 34 12 2 42 (a) First iteration. We find the minimal element, 0, at the last index, swapping it with the first element. At this point, the first element is sorted. 0 4 9 4 102 34 12 2 42 swap 0 2 9 4 102 34 12 4 42 (b) Second Iteration. Now starting with the second elem...
ComputerScienceOne_Page_257_Chunk1805
12. Searching & Sorting n−1 X i=1 i = n(n −1) 2 Another way to analyze the code is to count the number of comparisons with respect to the for loop index variables. In particular, there is one comparison made on line 4. Line 4 itself is executed once for each time the inner for loop on line 3 executes which executes for...
ComputerScienceOne_Page_258_Chunk1806
12.2. Sorting two elements are now sorted. If we continue this, then on the i-th iteration, the first i elements, a1, . . . , ai are sorted (just as with Selection Sort). Now consider the (i + 1)-th element: we will insert it amongst the elements a1, . . . , ai where it needs to be. We insert the “current” element, ai+1...
ComputerScienceOne_Page_259_Chunk1807
12. Searching & Sorting 42 4 9 4 102 34 12 2 0 4 42 9 4 102 34 12 2 0 (a) First iteration. We insert 4 in front of 42, requiring 1 comparison. 4 42 9 4 102 34 12 2 0 2 1 4 9 42 4 102 34 12 2 0 (b) Second iteration. The first two elements are sorted, we insert 9 by making two comparisons: to find that it is less than 42, ...
ComputerScienceOne_Page_260_Chunk1808
12.2. Sorting The i-th iteration would require i comparisons to move the current element all the way to the front of the collection. Again, this gives us a summation: n−1 X i=1 i = n(n −1) 2 matching the complexity of Selection Sort. We could also analyze Insertion Sort with respect to average case. On average, we woul...
ComputerScienceOne_Page_261_Chunk1809
12. Searching & Sorting i, j and increment/decrement them respectively to find a pair that are both in the wrong partitions, swapping them. The partitioning continues until the two index variables meet each other. As a final step, the pivot element is placed between the two partitions and the index at which it is placed ...
ComputerScienceOne_Page_262_Chunk1810
12.2. Sorting partitioning operations on subarrays as part of the recursion. Input : A collection A = {a1, . . . , an}, indices l, r Output : A, sorted in ascending order 1 if l < r then 2 p ←Partition(A, l, r) 3 QuickSort(A, l, p −1) 4 QuickSort(A, p + 1, r) 5 end Algorithm 12.6: QuickSort Input : A collection A = {a1...
ComputerScienceOne_Page_263_Chunk1811
12. Searching & Sorting 42 4 9 4 102 34 12 2 0 j i swap 42 4 9 4 0 34 12 2 102 i j (a) First iteration. 42 is chosen as the pivot element. The index variable i moves over to 102, the first element that is greater than 42 and on the “wrong” side of the partition. The j index variable does not move as 0 is less than the p...
ComputerScienceOne_Page_264_Chunk1812
12.2. Sorting 9 4 4 34 12 i, j 4 4 9 34 12 s (a) First (and only) iteration. In this parti- tioning, 9 is the pivot. The index variable i is incremented to 34 while j decrements to match. 34 is swapped with itself. After this iteration, the second condition applies and the pivot is swapped with ai−1 = 4 Figure 12.9.: E...
ComputerScienceOne_Page_265_Chunk1813
12. Searching & Sorting To analyze the number of comparisons in this case, we can setup a recurrence relation: C(n) = 2C n 2  + n Here, C(n) represents the number of comparisons made by Quick Sort on an array of size n. The first term on the right hand side represents the fact that we make 2 recursive calls on subarra...
ComputerScienceOne_Page_266_Chunk1814
12.2. Sorting Merge Sort works by first dividing the list into two (roughly) equal partitions. It then recursively sorts each partition. The recursion stops when the subarray is of size ≤1 just as with Quick Sort. The difference, however, is what Merge Sort does after the recursion. After having sorted the left partition...
ComputerScienceOne_Page_267_Chunk1815
12. Searching & Sorting Input : Two sorted collections, L, R of size n, m respectively. Output : A sorted collection A consisting of all elements of L and R 1 A ←a new, empty collection 2 i ←1 3 j ←1 4 k ←1 //index variable for A 5 6 while i ≤n And j ≤m do 7 if Li ≤Ri then 8 Ak ←Li 9 i ←(i + 1) 10 else 11 Ak ←Lj 12 j ←...
ComputerScienceOne_Page_268_Chunk1816
12.2. Sorting 42 4 9 4 102 34 12 2 42 4 9 4 102 34 12 2 42 4 9 4 102 34 12 2 42 4 9 4 102 34 12 2 4 42 4 9 34 102 2 12 4 4 9 42 2 12 34 102 2 4 4 9 12 34 42 102 merge merge merge merge merge merge merge Figure 12.10.: Illustration of Merge Sort’s recursion and merge operations. 235
ComputerScienceOne_Page_269_Chunk1817
12. Searching & Sorting 4 4 9 42 2 12 34 102 i j 2 k (a) Iteration One. L1 = 4 > R1 = 2, so the element in the right partition is copied into A1. Both j, k are incremented. 4 4 9 42 2 12 34 102 i j 2 4 k (b) Iteration Two. Now the element in the left partition is lesser and is copied, incrementing i, k 4 4 9 42 2 12 34...
ComputerScienceOne_Page_270_Chunk1818
12.2. Sorting Analysis Because Merge Sort divides the list first, an even split is guaranteed. After the recursion, the Merge subroutine requires at most n −1 comparisons to merge the two collections. This leads to a recurrence relation similar to Quick Sort, C(n) = 2C n 2  + (n −1) A similar analysis yields a complex...
ComputerScienceOne_Page_271_Chunk1819
12. Searching & Sorting or 1 septillion comparisons. The same sorting operation using either Quick Sort or Merge Sort would require only n log (n) = 1012 log 1012 ≈4 × 1013 or just under 40 trillion comparisons. This is 25 billion times fewer operations. As another example, suppose that we sort a collection with n elem...
ComputerScienceOne_Page_272_Chunk1820
12.3. Searching & Sorting In Practice been developed with thousands of man-hours and have proven themselves over millions of computing hours. Typically, searching and sorting functions in a language are made to be generic: they don’t just search a collection of numbers or strings. Instead, they accept collections of an...
ComputerScienceOne_Page_273_Chunk1821
12. Searching & Sorting Sorting Algorithm array Input sorted array Output Comparator a, b order =    < 0 if a < b 0 if a = b > 0 if a > b Figure 12.12.: Generalized Sorting with a Comparator. A sorting algorithm doesn’t need to know what it is sorting or how they are ordered as long as it has access to a comparator ...
ComputerScienceOne_Page_274_Chunk1822
12.3. Searching & Sorting In Practice 12.3.3. Avoiding the Difference Trick Another issue related to arithmetic overflow is a common “trick” used in comparators when ordering integer values. Consider the following example: we want to order integer values in ascending order, the basic logic would look something like the f...
ComputerScienceOne_Page_275_Chunk1823
12. Searching & Sorting an integer, truncating the fractional value, so that 0.1 →0, meaning that a GPA of 3.9 is “equivalent” to the 4.0. Given the potential for errors, it is best to avoid this trick altogether. 12.3.4. Importance of a Total Order In many applications it is important to design your comparator to prov...
ComputerScienceOne_Page_276_Chunk1824
12.3. Searching & Sorting In Practice Input : Two student objects, a, b 1 if a.year = b.year then 2 output 0 3 else if a.year = “Freshman′′ then 4 output −1 5 else if b.year = “Freshman′′ then 6 output 1 7 else if a.year = “Sophomore′′ then 8 output −1 9 . . . However, this logic is complex and does not provide a good ...
ComputerScienceOne_Page_277_Chunk1825
12. Searching & Sorting Sorting stability is often desirable for data presentation. A user can typically sort table data by clicking on a column header. Suppose we sorted a table of students first by GPA then by year. We would expect that all Freshman would be grouped together and within that group, would be ordered by ...
ComputerScienceOne_Page_278_Chunk1826
12.4. Exercises years are usually ordered Freshman, Sophomore, Junior, Senior whereas the natural ordering would order them Freshman, Junior, Senior, Sophomore. Write a program to sort a collection of strings according to an arbitrary artificial ordering. That is, instead of the A–Z alphabetic ordering, we will order th...
ComputerScienceOne_Page_279_Chunk1827
12. Searching & Sorting qetegyqelu For simplicity, you can assume that all words will be lower case and no non-alphabetic characters are used. However, you may not assume that all words will be the same length. Words of a shorter length that are a prefix of another word should be ordered first. For example, “newax” shoul...
ComputerScienceOne_Page_280_Chunk1828
13. Graphical User Interfaces & Event Driven Programming This chapter may appear in a future version. 247
ComputerScienceOne_Page_281_Chunk1829
14. Introduction to Databases & Database Connectivity This chapter may appear in a future version. 249
ComputerScienceOne_Page_283_Chunk1830
Part I. The C Programming Language 251
ComputerScienceOne_Page_285_Chunk1831
15. Basics The C programming language is a relatively old language, but still widely used. It is universal in that nearly every system, platform, and operating system has a C compiler that produces machine code for that system. C is used extensively in systems programming for operating system kernels, embedded systems,...
ComputerScienceOne_Page_287_Chunk1832
15. Basics 1 #include <stdlib.h> 2 #include <stdio.h> 3 4 /** 5 * Basic Hello World program in C 6 * Prints "Hello World" to the standard output and exits 7 */ 8 int main(int argc, char **argv) { 9 10 printf("Hello World\n"); 11 12 return 0; 13 } Code Sample 15.1.: Hello World Program in C “Hello World!” to the user in...
ComputerScienceOne_Page_288_Chunk1833
15.2. Basic Elements 15.2.1. Basic Syntax Rules C is a highly influential programming language. Many modern programming languages have adopted syntactic elements that originated in C. Usually such languages are referred to as “C-style syntax” languages. These elements include the following. • C is a statically typed lan...
ComputerScienceOne_Page_289_Chunk1834
15. Basics been implemented for us. The first, stdlib.h represents the C standard ( std ) library ( lib ). This library is so essential that many compilers will automatically include it even if you do not explicitly do so in your program. Still, it is best practice to include it in your code. The second, stdio.h is the ...
ComputerScienceOne_Page_290_Chunk1835
15.2. Basic Elements Function Description abs(x) Absolute value for int variables, |x|a fabs(x) Absolute value for double variables ceil(x) Ceiling function, ⌈46.3⌉= 47.0 floor(x) Floor function, ⌊46.3⌋= 46.0 cos(x) Cosine functionb sin(x) Sine functionb tan(x) Tangent functionb exp(x) Exponential function, ex, e = 2.7...
ComputerScienceOne_Page_291_Chunk1836
15. Basics 1 #define MILES_PER_KM 1.609 The macro defines an “alias” for the MILES_PER_KM identifier as the value 1.609. Essen- tially, the C preprocessor will go through the code and any instance of MILES_PER_KM will be replaced with 1.609 . The advantage of using a macro like this is that we can use the identifier MILES...
ComputerScienceOne_Page_292_Chunk1837
15.2. Basic Elements multiline comment will likely result in a compiler error but with color-coded comments its easy to see the mistake visually. 15.2.4. The main() Function Every executable program starts its execution somewhere. In C, the starting point is the main() function. When a program is compiled to an executa...
ComputerScienceOne_Page_293_Chunk1838
15. Basics 15.3. Variables As previewed, the three primary primitive types supported in C are int , double , and char which support integers, floating point numbers, and single ASCII characters. Integer ( int ) types are only guaranteed to “be at least” 16 bytes by the C standard but are usually 32-bit signed integers o...
ComputerScienceOne_Page_294_Chunk1839
15.3. Variables variable that we wish to assign the value to appears on the left-hand-side while the value (literal, variable or expression) is on the right-hand-size. Using our variables from before, we can assign them values: 1 numUnits = 42; 2 costPerUnit = 32.79; 3 firstInitial = 'C'; An important thing to understa...
ComputerScienceOne_Page_295_Chunk1840
15. Basics 1 const int secret = 42; 2 const double salesTaxRate = 0.075; Any attempt to reassign the values of const variables will result in a compiler error. 15.4. Operators C supports the standard arithmetic operators for addition, subtraction, multiplication, and division using + , - , * , and / respectively. Each ...
ComputerScienceOne_Page_296_Chunk1841
15.5. Basic I/O 10 / 20 , the result is not 0.5 as expected. The number 0.5 is a floating point number. As such, the fractional part gets truncated (cut offand thrown out) leaving only zero. In the code above, d = a / b; the variable d ends up getting the value zero because of this. Similarly, attempting to assign a float...
ComputerScienceOne_Page_297_Chunk1842
15. Basics for standard input. The printf() function works exactly as discussed in Section 2.4.3. The scanf() function works using similar placeholders as printf() . To illustrate how it works, consider the following lines of code: 1 int a; 2 printf("Please enter a number: "); 3 scanf("%d", &a); The printf() statement ...
ComputerScienceOne_Page_298_Chunk1843
15.6. Examples in zero as a legitimate input versus bad input. In general, scanf() is not a good mechanism for reading input (and in fact can be very dangerous), but it does provide a good starting point. 15.6. Examples 15.6.1. Converting Units Let’s write a program that will prompt the user to enter a temperature in d...
ComputerScienceOne_Page_299_Chunk1844
15. Basics 2. Next we’ll read the user’s input, likely into a floating point number as degrees can be fractional 3. Once we have the input, we can calculate the degrees Celsius by using the formula above 4. Lastly, we will want to print the result to the user to inform them of the value Sometimes its helpful to write an...
ComputerScienceOne_Page_300_Chunk1845
15.6. Examples use an ampersand when using scanf() : scanf("%lf", &fahrenheit); We can now compute celsius using the formula provided: celsius = (fahrenheit - 32) * (5 / 9); Finally, we use printf() again to output the result to the user: printf("%f Fahrenheit is %f Celsius\n", fahrenheit, celsius); Try typing and runn...
ComputerScienceOne_Page_301_Chunk1846
15. Basics 1 #include <stdlib.h> 2 #include <stdio.h> 3 4 /** 5 * This program converts Fahrenheit temperatures to 6 * Celsius 7 */ 8 int main(int argc, char **argv) { 9 10 double fahrenheit, celsius; 11 12 //1. Prompt the user for input in Fahrenheit 13 printf("Please enter degrees in Fahrenheit: "); 14 15 //2. Read t...
ComputerScienceOne_Page_302_Chunk1847
15.6. Examples the formula leads to 1 root1 = (-b + sqrt(b*b - 4*a*c) ) / (2*a); 2 root2 = (-b - sqrt(b*b - 4*a*c) ) / (2*a); Finally, we print the output using printf() . The full program can be found in Code Sample 15.3. 1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <math.h> 4 5 /** 6 * This program computes ...
ComputerScienceOne_Page_303_Chunk1848
15. Basics inputs as command line arguments, converting them to floating point numbers. Lines 12–17 in the program could have been changed to 1 a = atof(argv[1]); 2 b = atof(argv[2]); 3 c = atof(argv[3]); Finally, think about the possible inputs a user could provide that may cause problems for this program. For example:...
ComputerScienceOne_Page_304_Chunk1849
16. Conditionals C supports the basic if, if-else, and if-else-if conditional structures as well as switch statements. Logical statements are built using the standard logical operators for numeric comparisons as well as logical operators such as negation, And, and Or. However, there are a few idiosyncrasies that need t...
ComputerScienceOne_Page_305_Chunk1850
16. Conditionals Name Operator Syntax Examples Value Equals == a == 10 true b == 10 false a == b false a == c true Not Equals != a != 10 false b != 10 true a != b true a != c false Strictly Less Than < a < 15 true a < 5 false a < b true a < c false Less Than Or Equal To <= a <= 15 true a <= 5 false a <= b true a <= c t...
ComputerScienceOne_Page_306_Chunk1851
16.1. Logical Operators Operator(s) Associativity Notes Highest ++ , -- left-to-right increment operators - , ! right-to-left unary negation operator, logical not * , / , % left-to-right + , - left-to-right addition, subtraction < , <= , > , >= left-to-right comparison == , != left-to-right equality, inequality && left...
ComputerScienceOne_Page_307_Chunk1852
16. Conditionals Comparison Example Result ('A' < 'a') true ('A' == 'a') false ('A' < 'Z') true ('0' < '9') true ('\n' < 'A') true (' ' < '\n') false Table 16.4.: Character comparisons in C understand that you can write this code, it will compile, and it will even run. However, the results will not be as expected. 16.2...
ComputerScienceOne_Page_308_Chunk1853
16.2. If, If-Else, If-Else-If Statements 1 //example of an if statement: 2 if(x < 10) { 3 printf("x is less than 10\n"); 4 } 5 6 //example of an if-else statement: 7 if(x < 10) { 8 printf("x is less than 10\n"); 9 } else { 10 printf("x is 10 or more \n"); 11 } 12 13 //example of an if-else-if statement: 14 if(x < 10) {...
ComputerScienceOne_Page_309_Chunk1854
16. Conditionals 4 printf("x is less than 10\n"); This is obviously not what we wanted. The semicolon ended up binding to the empty executable statement. The code block containing the print statement immediately followed, but it was not bound to the conditional statement which is why the print statement executed regard...
ComputerScienceOne_Page_310_Chunk1855
16.3. Examples log(x) / log(b) But wait: we have a problem similar to the examples in the previous section. The user could enter invalid values such as b = −10 or x = −2.54 (logarithms are undefined for non-positive values in any base). We want to ensure that b > 1 and x > 0. With conditionals, we can now do this. Once ...
ComputerScienceOne_Page_311_Chunk1856
16. Conditionals 6 printf("How many children do you have?"); 7 scanf("%d", &numChildren); 8 9 if(income < 0 || numChildren < 0) { 10 printf("Invalid inputs"); 11 exit(1); 12 } Next, we can code a series of if-else-if statements for the income range. By placing the ranges in increasing order, we only need to check the u...
ComputerScienceOne_Page_312_Chunk1857
16.3. Examples 1 if(baseTax - credit >= 0) { 2 totalTax = baseTax - credit; 3 } else { 4 totalTax = 0; 5 } The full program is presented in Code Sample 16.3. 16.3.3. Quadratic Roots Revisited Let’s return to the quadratic roots program we previously designed that uses the quadratic equation to compute the roots of a qu...
ComputerScienceOne_Page_313_Chunk1858
16. Conditionals 1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <math.h> 4 5 /** 6 * This program computes the logarithm base b (b > 1) 7 * of a given number x > 0 8 */ 9 int main(int argc, char **argv) { 10 11 double b, x, result; 12 if(argc != 3) { 13 printf("Usage: %s b x \n", argv[0]); 14 exit(1); 15 } 16 17...
ComputerScienceOne_Page_314_Chunk1859
16.3. Examples 1 #include <stdlib.h> 2 #include <stdio.h> 3 4 int main(int argc, char **argv) { 5 6 double income, baseTax, credit, totalTax; 7 int numChildren; 8 9 //prompt for income from the user 10 printf("Please enter your Adjusted Gross Income: "); 11 scanf("%lf", &income); 12 13 //prompt for children 14 printf("...
ComputerScienceOne_Page_315_Chunk1860
16. Conditionals 1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <math.h> 4 5 /** 6 * This program computes the roots to a quadratic equation 7 * using the quadratic formula. 8 */ 9 int main(int argc, char **argv) { 10 11 double a, b, c, root1, root2; 12 13 if(argc !=4) { 14 printf("Usage: %s a b c\n", argv[0]); ...
ComputerScienceOne_Page_316_Chunk1861
17. Loops C supports while loops, for loops, and do-while loops using the keywords while , for , and do (along with another while ). Continuation conditions for loops are enclosed in parentheses, (...) and the blocks of code associated with the loop are enclosed in curly brackets. 17.1. While Loops Code Sample 17.1 con...
ComputerScienceOne_Page_317_Chunk1862
17. Loops 1 int i = 1; 2 int flag = 1; 3 while(flag) { 4 //perform some action 5 i++; //iteration 6 if(i>10) { 7 flag = 0; 8 } 9 } Code Sample 17.2.: Flag-controlled While Loop in C A similar problem occurs: the while keyword and continuation condition bind to the next executable statement or code block. As a consequen...
ComputerScienceOne_Page_318_Chunk1863
17.2. For Loops 17.2. For Loops For loops in C use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the keyword for . An example can be found in Code Sample 17.3. 1 int i; 2 for(i=1; i<=10; i++) { 3 //perform some action 4 } Code Sample 17.3.: For Loop in C Se...
ComputerScienceOne_Page_319_Chunk1864
17. Loops 1 int i; 2 do { 3 //perform some action 4 i++; 5 } while(i<=10); Code Sample 17.4.: Do-While Loop in C appear at the end of the continuation condition even though it is not an executable statement. 17.4. Other Issues C does not support a traditional foreach loop. When iterating over a collection like an array...
ComputerScienceOne_Page_320_Chunk1865
17.5. Examples 17.5. Examples 17.5.1. Normalizing a Number Let’s revisit the example from Section 4.1.1 in which we normalize a number by continually dividing it by 10 until it is in the range [1, 10). The code in Code Sample 17.5 specifically refers to the value 32145.234 but would work equally well with any non-negati...
ComputerScienceOne_Page_321_Chunk1866
17. Loops 1 for(i=1; i<=n; i++) { 2 sum += i; 3 } 17.5.3. Nested Loops Recall that you can write loops within loops. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in C can be found in Code Sample 17.7. 1 int i, j; 2 int n = 10; 3 int m = 20; 4 for(i=0; i<n; i+...
ComputerScienceOne_Page_322_Chunk1867
17.5. Examples 1 double monthlyPayment = (monthlyInterestRate * principle) / 2 (1 - pow( (1 + monthlyInterestRate), -n)); However, recall that we may have problems due to accuracy. The monthly payment could come out to be a fraction of a cent, say $43.871. For accuracy, we need to ensure that all of the figures for curr...
ComputerScienceOne_Page_323_Chunk1868
17. Loops 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <math.h> 4 5 int main(int argc, char **argv) { 6 7 if(argc != 4) { 8 printf("Usage: %s principle apr terms\n", argv[0]); 9 exit(1); 10 } 11 12 double principle = atof(argv[1]); 13 double apr = atof(argv[2]); 14 int n = atoi(argv[3]); 15 16 double balance =...
ComputerScienceOne_Page_324_Chunk1869
18. Functions As a procedural-style language, functions are essential in C programming. As we’ve already seen, C provides a large library of standard functions to perform basic input/output, math, and many other functions. C also provides the ability to define and use your own functions. When you define functions in C, c...
ComputerScienceOne_Page_325_Chunk1870
18. Functions Typically, the documentation for functions is included with the prototype but is not repeated with the function definition. This is a principle known as Don’t Repeat Yourself (DRY). Consider the following examples. In these examples we use a commenting style known as “doc comments.” This style was original...
ComputerScienceOne_Page_326_Chunk1871
18.1. Defining & Using Functions 4 5 double getDistance(double x1, double y1, double x2, double y2) { 6 double xDiff = (x1-x2); 7 double yDiff = (y1-y2); 8 return sqrt( xDiff * xDiff + yDiff * yDiff); 9 } 10 11 double getMonthlyPayment(double principle, double apr, int terms) { 12 double rate = (apr / 12.0); 13 double p...
ComputerScienceOne_Page_327_Chunk1872
18. Functions 18.1.3. Organizing Functions The separation of a function declaration (prototype) and a function definition provides a natural way to organize functions in C. We place prototypes into a header file which has a file extension .h and then place the corresponding function definitions into a source file with the fi...
ComputerScienceOne_Page_328_Chunk1873
18.2. Pointers 9 double r = 0.05; 10 double monthlyPayment = getMonthlyPayment(p, r, 60); By default, all primitive types including int , double , and char are passed by value. To be able to pass arguments by reference, we need to use pointers. 18.2. Pointers Consider the following line of C code. int a = 10; This line...
ComputerScienceOne_Page_329_Chunk1874
18. Functions Though syntactically this makes sense (and generally the compiler will let you do this with at most a warning), it is not really what you want. This assigns to the pointer variable ptrA the value 10, which will be interpreted as the memory address 10. This memory address may not belong to your program, or...
ComputerScienceOne_Page_330_Chunk1875
18.2. Pointers NULL using the usual equality operator. 1 int *ptrA = NULL; 2 ... 3 if(ptrA == NULL) { 4 printf("Error: invalid memory location\n"); 5 } Dereferencing Operator Once we have a valid pointer to a memory location, we may want to manipulate the contents of the memory it references. To do this we use the inve...
ComputerScienceOne_Page_331_Chunk1876
18. Functions 0xc260ec80 0xc260ec84 10 a 0xc260ec88 0xf289fb14 0xf289fb18 ptrA NULL 0xc260ec88 ... Address Contents (a) After the first two lines memory has been dedicated for the variable a and the pointer variable ptrA and their values have been initialized. 0xc260ec80 0xc260ec84 10 a 0xc260ec88 0xf289fb14 0xf289fb18 ...
ComputerScienceOne_Page_332_Chunk1877
18.2. Pointers used with pointer variables. 1 //prototypes 2 /** 3 * This function sums the first two variables (passed by 4 * value) and places the result into the third variable 5 * (passed by reference). 6 */ 7 void sum(int a, int b, int *c); 8 9 /** 10 * This function swaps the values stored in the 11 * two variabl...
ComputerScienceOne_Page_333_Chunk1878
18. Functions 4 int *ptrC = &c; 5 sum(x, y, ptrC); 6 //at this point c contains the value 30 7 8 swap(&x, &y); 9 //at this point, the values in x and y have been swapped 10 // x contains 20 and y contains 10 This should look familiar. We saw this same syntax when we used scanf() to read input from the standard input. W...
ComputerScienceOne_Page_334_Chunk1879
18.3. Examples double x = ptrToSqrt(2.0); Some more examples: 1 //this pointer can point any function that takes 2 //three arguments: an int, double, and a char 3 //and returns an int value 4 int (*ptrToFunc)(int, double, char)= NULL; 5 6 double x; 7 double (*ptr)(double) = NULL; 8 //we can make it point to sqrt: 9 ptr...
ComputerScienceOne_Page_335_Chunk1880
18. Functions in the math library’s round() function. We could further define a roundToCents() function that used our generalized round function. Let’s also think about organization. We could place the prototypes into a round.h header file and the corresponding definitions in a round.c source file. The contents of these tw...
ComputerScienceOne_Page_336_Chunk1881
18.3. Examples 18.3.2. Quadratic Roots Another advantage of passing variables by reference is that we can “return” multiple values with one function call. Functions are limited in that they can only return at most one value. But if we pass multiple parameters by reference, the function can manipulate the contents of th...
ComputerScienceOne_Page_337_Chunk1882
19. Error Handling The C language does not support exceptions or exception handling. Instead, the usual method of error handling is done through defensive programming. As a user, it is your responsibility to write code that checks for invalid or unsafe operations before executing them and handle the error appropriately...
ComputerScienceOne_Page_339_Chunk1883
19. Error Handling with a zero value results in an ERANGE error as C does not support −∞as an actual number. • EILSEQ indicates an illegal byte sequences in characters on systems that use UTF-8. All three of these are defined in the errno.h header file. Depending on the system, additional error codes may also be defined a...
ComputerScienceOne_Page_340_Chunk1884
19.1. Language Supported Error Codes 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <math.h> 4 #include <string.h> 5 #include <errno.h> 6 7 int main(int argc, char **argv) { 8 9 double a = -1, b = 2, c = 0.0; 10 double x; 11 12 //okay 13 x = sqrt(b); 14 printf("result: %.4f, error: %d\n", x, errno); 15 16 //NaN ...
ComputerScienceOne_Page_341_Chunk1885
19. Error Handling can be used beyond the three mentioned above. For example, the ENOENT error code corresponds to “No such file or directory” and EACCES corresponds to a “Permission denied” error. 19.2. Error Handling By Design In our own code we could communicate errors to calling functions by setting the errno variab...
ComputerScienceOne_Page_342_Chunk1886
19.3. Enumerated Types error code it returned and handle the error in whatever way it wants. There is still an issue, however. The usage of the integers 1, 2, 3 to indicate the various errors was arbitrary. These are essentially magic numbers that the calling function would have to deal with by making comparisons with ...
ComputerScienceOne_Page_343_Chunk1887
19. Error Handling values it can take are SUNDAY , MONDAY , etc. and we can use these keywords in our program. For example, 1 DayOfWeek today = MONDAY; 2 3 if(today == SUNDAY || today == SATURDAY) { 4 printf("It is the weekend!\n"); 5 } Note the modern naming conventions: the type identifier uses upper camel casing whil...
ComputerScienceOne_Page_344_Chunk1888
19.4. Using Enumerated Types for Error Codes 1 typedef enum { 2 NO_ERROR, 3 DIV_BY_ZERO_ERROR, 4 COMPLEX_ROOT_ERROR, 5 NULL_POINTER_ERROR 6 } ErrorCode; Now in the quadraticRoots() function, we can return the appropriate error code as an enumerated type value. 1 ErrorCode quadraticRoots(double a, double b, double c, 2 ...
ComputerScienceOne_Page_345_Chunk1889
20. Arrays C allows you to declare and use arrays. Since C is statically typed, arrays must also be typed when they are declared and may only hold that particular type of element. C supports the use of both static arrays and dynamic arrays through standard library calls. 20.1. Basic Usage To declare a static array, you...
ComputerScienceOne_Page_347_Chunk1890
20. Arrays Variable Length Arrays C99 introduced Variable Length Arrays (VLAs, which are also supported in GNU C89) which allow you to declare a static array whose size is determined by a variable. For example, 1 int n = 5; 2 int arr[n]; or within a function, 1 void foo(int n) { 2 int arr[n]; 3 ... 4 } In either case, ...
ComputerScienceOne_Page_348_Chunk1891
20.1. Basic Usage Recall that an index is actually an offset. The compiler and system know exactly how many bytes each int element takes and so an index i calculates exactly how many bytes from the first element the i-th element is located at. Consequently it is possible to index elements that are beyond the range of the...
ComputerScienceOne_Page_349_Chunk1892
20. Arrays 20.2. Dynamic Memory Recall that static arrays have many shortcomings (see Section 7.2). In general they should be avoided since stack space is limited and they cannot be returned from functions. Fortunately, C provides several standard library functions that facilitate the creation and management of dynamic...
ComputerScienceOne_Page_350_Chunk1893
20.2. Dynamic Memory 5 values = (double *) malloc(sizeof(double) * 100); The pointer cast is just like when we casted int types as double types so that we could perform division without truncation. In this case, we convert the returned generic void pointer into a int pointer and double pointer respectively.1 Once creat...
ComputerScienceOne_Page_351_Chunk1894
20. Arrays Deallocation Once dynamically allocated memory is no longer needed, we should release it so that it can be reused by the program or the operating system. The free() function in the standard library does this for us. All we need to do is provide the pointer to free() and it deallocates the memory block. 1 fre...
ComputerScienceOne_Page_352_Chunk1895
20.4. Multidimensional Arrays In this example we had no need to make changes to any of the elements in the array. However, the array was still passed by reference, meaning we could have. When passing arrays, we can use the keyword const (short for constant) to explicitly indicate that no changes will be made to the arr...
ComputerScienceOne_Page_353_Chunk1896
20. Arrays array of, say, integers can be modeled as an array of pointers that point to an array of integers. That is, a pointer to pointers, for example, int ** . The initial pointer points to an array of integer pointers, int * and each integer pointer points to an array of int variables. To understand this better, l...
ComputerScienceOne_Page_354_Chunk1897
20.4. Multidimensional Arrays **myMatrix *myMatrix[0] ? *myMatrix[1] ? *myMatrix[2] ? ... *myMatrix[n-1] ? (a) Initialization of the pointer-to-pointers. The first invocation of malloc() sets up an array of integer pointers, int * that are uninitialized (where they point to is undefined). **myMatrix *myMatrix[0] myMatrix...
ComputerScienceOne_Page_355_Chunk1898
20. Arrays 1 for(i=0; i<n; i++) { 2 free(myMatrix[i]); 3 } 4 free(myMatrix); 20.4.1. Contiguous 2-D Arrays The example depicted in Figure 20.1 constructs a two dimensional array. However, each “row” of the array was created using an independent call to malloc() which may result in non-contiguous memory blocks (each row...
ComputerScienceOne_Page_356_Chunk1899
20.4. Multidimensional Arrays Now we can treat the array like we would any other two dimensional array by specifying two indices. 1 for(i=0; i<4; i++) { 2 for(j=0; j<3; j++) { 3 arr[i][j] = 10 * i + j; 4 } 5 } Which would result in an array that, conceptually, looks something like the following. [ 0 1 2 ] [ 10 11 12 ] ...
ComputerScienceOne_Page_357_Chunk1900