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 0 1 Total log2 (n) + 1 Table 12.1.: Number of comparisons and array size after the iteration during the execution of binary search. Comparative Analysis Binary search presents a clear advantage over linear search. There is an exponential difference between a linear function, n 2 and a logarithmic function, log2 (n). To put this in perspective, consider searching a moderately large database of 1 trillion (1012) records.3 Using linear search, even the average-case scenario would require about 1012 2 = 5 × 1011 or about 500 billion comparisons. However, using binary search would only require at most log2 (1012) = 12 · log2 (10) < 40 comparisons to search. This is a huge difference in performance. As another comparison, let’s consider how each algorithm’s complexity grows as we increase the size of the collection being searched. As observed earlier, if we double the 3In the era of “big data,” 1 trillion records only qualifies as moderately large. 219
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 an array of twice the size. The difference between these two algorithms shows up in many different instances. Figure 12.4 contains a screen shot of the search feature in Windows 7. When searching for particular files or content in particular files, the search can be greatly increased if the files have been indexed, that is, sorted. As the dialog indicates, non-indexed (unsorted) records will take far longer to search. Figure 12.4.: Example of the benefit of ordered (indexed) elements in Windows 7 Though binary search presents a clear advantage over linear search, it only works if the collection has been sorted.4 Thus, we now turn our attention to the problem of sorting a collection. 12.2. Sorting Sorting a collection of data is another fundamental data operation. It is conceptually simple, but is ubiquitous. There are a large variety of algorithms, data structures and applications built around the problem of sorting. As we’ve already seen, being able to sort a collection provides a huge speed up when searching for a particular element. Sorting provides a natural way to store and organize data. Problem 2 (Sorting). Given: a collection of orderable elements, A = {a1, a2, . . . , an} Output: A, sorted in ascending order The requirement that the collection be made of “orderable” elements can be a bit technical5, but essentially we need to be guaranteed that given two elements, a, b in the 4Binary search also only works when searching an array with random access to its elements. The performance of binary search cannot generally be realized with data structures such as linked lists or unordered sets. 5We require that A be a total order a partially ordered binary relation such that all pairs are comparable. 220
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 permuted (that is, reordered) or we may instead want a copy of the collection to be created and sorted so that the original is unchanged. We will examine several standard sorting algorithms. Though there are dozens of sorting algorithms, we will only focus on a few of the more common ones. As with searching, we can analyze a sorting algorithm based on the number of comparisons it makes in the worst, best, or average cases. We may also look at alternative resources or operations: how many swaps does the algorithm make? How much extra memory is required? Etc. Though we will examine, analyze and compare several sorting algorithms, most pro- gramming languages provide standard functionality to sort a collection of elements. It is generally preferable to use the functionality built into whatever language you’re using rather that reimplementing your own. Typically, these functions are well-designed, well-tested, optimized and more efficient than any custom alternatives. 12.2.1. Selection Sort The first sorting algorithm we’ll examine is Selection Sort which is similar to the way a human would sort a collection of objects. The basic idea is that you search through the collection and find the minimal element (we say minimal and not minimum because there could be elements with the same value). Once we’ve found a minimal element, we can swap it with the “first” element, a1, placing the minimal element where it belongs in the collection. We repeat this process for the remaining elements, a2, . . . , an, finding the minimal element among these and swapping with a2. In general, if we have already sorted the first i −1 elements, a1, . . . , ai−1 then we only need to examine the elements ai, . . . , an for the minimal element, swapping it with ai. We end this process after we have sorted the first n −1 elements, a1, . . . , an−1 since the last element an will already be where it needs to be. We present Selection Sort as Algorithm 12.4. We illustrate the execution of Selection 6Technically, these are referred to as non-decreasing and non-increasing respectively. This is because the collection could contain duplicate elements and not lead to a strictly increasing or strictly decreasing ordering. 221
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: Selection Sort Analysis We now analyze Selection Sort to determine how complex it is. First, the elementary operation is the comparison on line 4. We need to determine how many times this line is executed with respect to the size of the input, n. Observe that on the i-th iteration, the first i −1 elements are sorted and we need not make any comparisons among them. We start by assuming that the ai is the minimum element and compare it to the remaining n −i elements, requiring n −i comparisons, to find the minimal element. For example, in the first iteration we make n −1 comparisons, the second we make n −2, etc. The last iteration we make only 1 comparison. Totaling these all up gives us (n −1) + (n −2) + (n −3) + · · · + 3 + 2 + 1 Which can be rewritten as n−1 X i=1 i = 1 + 2 + 3 + · · · + (n −2) + (n −1) We can use Gauss’s Formula to solve this summation. Theorem 1 (Gauss’s Formula). The sum of integers 1 up to n can be written as follows. n X i=1 i = 1 + 2 + 3 + · · · + (n −1) + n = n(n + 1) 2 In Selection Sort, the number of comparisons doesn’t sum up to n, only n−1. Substituting this in gives us 222
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 element, the minimal element among the remaining is found at the second to last element. 4 and 2 are swapped. At this point, the first two elements are sorted. 0 2 9 4 102 34 12 4 42 swap 0 2 4 9 102 34 12 4 42 (c) Third iteration. Since we are using the strictly-less than comparison, the first 4 is the minimal element and swapped with 9. 0 2 4 9 102 34 12 4 42 swap 0 2 4 4 102 34 12 9 42 (d) Fourth iteration. At this point, the first 3 elements are sorted. We find the minimal element (the other 4) and swap it with 9. At the end of this iteration, the first 4 elements are sorted. 0 2 4 4 102 34 12 9 42 swap 0 2 4 4 9 34 12 102 42 (e) Fifth iteration. The 9 is swapped with 102, sorting the first 5 elements. 0 2 4 4 9 34 12 102 42 swap 0 2 4 4 9 12 34 102 42 (f) Sixth iteration. 12 is swapped with 34. 0 2 4 4 9 12 34 102 42 swap 0 2 4 4 9 12 34 102 42 (g) Seventh iteration. 34 ends up being the minimal element and we essen- tially swap it with itself. Even though the “current” element was also the minimal element, we still had to compare the current element with all other elements; in this case we made 2 comparisons. 0 2 4 4 9 12 34 102 42 swap 0 2 4 4 9 12 34 42 102 (h) Eighth iteration. This is the final iteration, we swap 42 and 102. After this iteration, the final element, 102 is already where it belongs. Figure 12.5.: Example execution of Selection Sort. 223
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 j running from i + 1 up to n. Line 3 and the entire inner for loop executes once for each time the outer for loop executes, that is for i running from 1 up to n −1. This gives us the following summation. n−1 X i=1 n X j=i+1 1 |{z} line 4 | {z } line 3 | {z } line 1 Solving this summation gives us: n−1 X i=1 n X j=i+1 1 = n−1 X i=1 n −i = n−1 X i=1 n − n−1 X i=1 i = n(n −1) −n(n −1) 2 = n(n −1) 2 This illustrates that Selection Sort is a quadratic sorting algorithm, requiring roughly n2 comparisons to sort an array of n elements. We analyze this further below. 12.2.2. Insertion Sort Another basic sorting algorithm is Insertion Sort which works slightly differently than Selection Sort. Rather than finding a minimal element and swapping with the “current” element, the current element is inserted in the list where it belongs. If we consider just the first element, the collection is sorted by definition. Now consider the second element: either its greater than the first element and so is already sorted, or it is less than the first element and needs to be swapped. In either case, the first 224
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 by comparing it to ai: if ai > ai+1, then we swap them. We keep comparing the current element to the one immediately to its left, shifting the current element down the collection until we find an element that is less than or equal to the current element at which point we stop. Now the elements a1, . . . , ai+1 are now sorted. In contrast to Selection Sort, we do need to process the last element as it might not be where it needs to be. The full pseudocode is presented in Algorithm 12.5. An example of an execution of Insertion Sort can be found in Figure12.6. Input : A collection A = {a1, . . . , an} Output : An array A′ containing all elements of A in nondecreasing order 1 for i = 2, . . . , n do 2 x ←ai 3 j ←i 4 while j > 1 and aj−1 > x do 5 aj ←aj−1 6 decrement j 7 end 8 aj ←x 9 end Algorithm 12.5: Insertion Sort Analysis As we can see in the example run of Insertion Sort, not every iteration needs to make comparisons with all elements in the sorted part of the collection. For example, in iteration 4 we only had to make one comparison and we were done. In other iterations such as the last two, we had to make comparisons to every element in the sorted part of the collection. This illustrates that Insertion Sort is adaptive and may have a different complexity depending on the structure of the collection it sorts. Let’s consider the best case in which the number of comparisons is minimized. Suppose, for example, we ran Insertion Sort on a collection that was already sorted. Each iteration would only need one comparison to determine that the element was already where it needed to be. As there are only n −1 iterations, in the best case, Insertion Sort makes n −1 comparisons. In contrast, the worst case would occur if the list was already sorted, but in reverse order. 225
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, but greater than 4. At the end of the iteration, the first three elements are sorted. 4 9 42 4 102 34 12 2 0 3 2 1 4 4 9 42 102 34 12 2 0 (c) Third iteration. The first three elements are sorted, we insert the second four by making 3 comparisons. 4 4 9 42 102 34 12 2 0 1 4 4 9 42 102 34 12 2 0 (d) Fourth iteration. Here, only one comparison is necessary to find that 102 is already sorted. 4 4 9 42 102 34 12 2 0 1 2 3 4 4 9 34 42 102 12 2 0 (e) Fifth iteration. Here, 3 comparisons are necessary to insert 34 between 9 and 42. 4 4 9 34 42 102 12 2 0 1 2 3 4 4 4 9 12 34 42 102 2 0 (f) Sixth iteration. Here, 4 comparisons are necessary to insert 12 between 9 and 34. 4 4 9 12 34 42 102 2 0 1 2 3 4 5 6 7 2 4 4 9 12 34 42 102 0 (g) Seventh iteration. Here, the number of comparisons is maximized as we shift 2 all the way to the front of the array. Figure 12.6.: Example execution of Insertion Sort. Each iteration depicts the comparisons to previous elements; the last comparison is dashed indicating a comparison was made, but not a swap. The final iteration is omitted for space, but would require 8 comparisons to insert 0 at the front of the collection. 226
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 would expect to make about 1 2 of the total possible comparisons on each iteration. That is, n−1 X i=1 i 2 Moving the constant outside the summation and applying Gauss’s Formula would give us an expected number of comparisons to be n(n −1) 4 This is still a quadratic function, but the constant involved and the fact that Insertion Sort is more adaptive to the input make Insertion Sort a much better algorithm in practice than Selection Sort. In fact, Insertion Sort is very efficient on “small” arrays in practice and is used in many hybrid algorithm implementations (see Section 12.2.5). 12.2.3. Quick Sort Selection Sort and Insertion Sort are simple algorithms, but inefficient, making a quadratic number of comparisons in even the average case. A more sophisticated and efficient algorithm is Quick Sort, first developed by Tony Hoare in the early 1960s [17, 18]. Quick Sort is a divide-and-conquer style algorithm that attempts to solve the sorting problem by splitting a collection up into two parts, then recursively sorting each part. The basic idea is as follows. First, choose a pivot element p in the collection. We will then partition all the elements in the collection around this pivot element by placing all elements less than p in the “left” partition and all elements greater than p in the “right” partition. This concept is similar to binary search. After partitioning all the elements, we place p between them so that p is where it needs to be. We then repeat this process on the two partitions recursively. The recursion stops when the size of the sub-collection is trivially sorted (it is empty or consists of a single element). Quick Sort is presented as Algorithm 12.6 with a partitioning subroutine presented in Algorithm 12.7. The partitioning chooses the first element in the sub-collection as the pivot element. Further, the partitioning is done in-place: we maintain two index variables, 227
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 is returned to the main QuickSort routine so that it can make two recursive calls on the two partitions. We depict a few examples of the partitioning algorithm. Figure 12.7 depicts the first partitioning on the same example array while Figures 12.8 and 12.9 depict subsequent 228
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, . . . , an}, indices l, r Output : An index s such that the sub-collection A from l to r has been partitioned around s so that all elements al, . . . as−1 are less than as and all elements as+1, . . . , ar are greater than as 1 pivot ←al 2 i ←(l + 1) 3 j ←r 4 while i < j do 5 while i < j And ai ≤pivot do 6 i ←(i + 1) 7 end 8 while i < j And aj ≥pivot do 9 j ←(j −1) 10 end 11 swap ai, aj 12 end //Swap the pivot 13 if ai ≤pivot then 14 swap pivot, ai 15 output i 16 else 17 swap pivot, ai−1 18 output (i −1) 19 end Algorithm 12.7: In-Place Partition 229
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 pivot element and on the wrong side; these are swapped. 42 4 9 4 0 34 12 2 102 j i 2 4 9 4 0 34 12 42 102 s (b) Second iteration. The index variable i moves all the way to the right as all remaining elements are less than the pivot, 42. The index variable j remains at 102 as i is now equal to j. The pivot, 42 is placed between the two partitions and its resulting index, s is returned. Figure 12.7.: Example execution of the Partition subroutine in Quick Sort. A total of 8 comparisons are made, 9 if you count the last swap outside the while loop. The partition returns s as the pivot position; the right-partition is sorted as it only consists of 1 element. 2 4 9 4 0 34 12 j i swap 2 0 9 4 4 34 12 i j (a) First iteration. In this partitioning, 2 is the pivot element. The index variable i is not incremented as 4 is larger than the pivot. The index variable j decrements to 0 and they are swapped. 2 0 9 4 4 34 12 i, j 0 2 9 4 4 34 12 s (b) Second iteration. The index variable i is incremented once, while j is decremented to meet it. After the while loop the second case applies as ai = 9 > 2 = pivot, and so we swap ai−1 = 2 with the pivot. Figure 12.8.: Example execution of the Partition subroutine in Quick Sort on the first recursive call on the left partition. A total of 6 comparisons are made, 7 if you count the last swap outside the while loop. The partition returns s as the pivot position; in this case the left-partition is sorted as it only consists of 1 element. 230
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.: Example execution of the Partition subroutine in Quick Sort on the second recursive call on the right partition. A total of 5 comparisons are made, 6 if you count the last swap outside the while loop. The partition returns s as the pivot position. Analysis We can easily analyze how many comparisons are made by the Partition subroutine. Suppose that we are given a (sub)array of n elements. Since the pivot element must be compared to every other element in the (sub)array, it must make n −1 comparisons to partition the elements around the pivot. If we count the last comparison to determine where to place the pivot, it would be n comparisons (but the difference is trivial). The analysis of Quick Sort itself is a bit more involved and is highly dependent on how well the Partition subroutine splits the array. In the worst case, our pivot choice will always partition the array into one “empty” subarray and one subarray with n −1 elements (we do not count the pivot element). One such example of this would be if our collection is already sorted. In this case, one of the recursive calls would result in no comparisons and the other would result in n −1 comparisons. This lopsided recursion would result in the following number of comparisons: n + (n −1) + (n −2) + · · · + 3 + 2 + 1 which is exactly Gauss’s Formula, meaning that Quick Sort would perform n(n + 1) 2 in the worst case. However, in the sorting scenario, we cannot always assume the worst case. If we are given random data, then the likelihood that we will always have such an extremely lopsided partitioning is extremely small. A more reasonable analysis would involve the average case: where each partition is roughly an equal size, about n 2. This happens when our pivot choice is the median (or close to the median) element. 231
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 subarrays of size (roughly) n 2. The second term captures the number of comparisons we make in the Partition subroutine. Solving this recurrence is a bit beyond the scope of the current discussion. However, it can be shown that this is roughly equivalent to n log (n) comparisons in the best case. The difference between the best and worst case scenarios is in our pivot choice. Though the ideal pivot choice is the median element, to find the median the usual strategy is to sort the collection first. This puts the cart before the horse. If the data we are sorting is in more-or-less random order, then the choice of the first element as a pivot is good enough as it is unlikely that we will always have a bad paritioning. However, there are other strategies. One strategy is to randomly choose a pivot element. A random choice would make the worst-case scenario very unlikely over many runs of the algorithm. Another strategy is to choose the median of three elements (either fixed or randomized), ensuring that neither partition will ever be empty. This strategy can be taken further to find the median-of-three amongst each third of the array and then take the median of these (or the “ninther”). The more effort you put into finding the median the more the performance degrades in practice.7 A more sophisticated analysis of these strategies yields a complexity similar to the best case [9]. 12.2.4. Merge Sort Another “fast” sorting algorithm is Merge Sort, due to John von Neumann, 1945 (as reported by Knuth [27]). The performance is similar to Quick Sort’s best/average case, making n log (n) comparisons. However, Merge Sort’s performance does not depend on the structure of the input array or a pivot choice, guaranteeing this performance in the best/average/worst case.8 7For example, there does exist a median-finding algorithm that runs in linear time which would guarantee the theoretically best running time, but the algorithm is recursive and has a large overhead, making its use slow in practice. 8Still, Quick Sort is still more common in practice because it has less memory requirements and the pivot choice strategies can mitigate the risk of the worst-case scenario. 232
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, L and the right partition R, Merge Sort merges the two sorted partitions into one. The Merge subroutine works by maintaining two index variables, i, j, one for each partition. Suppose that the index variables correspond to the elements Li and Rj in the left/right partition. If Li ≤Rj, we add Li to the end of a temporary array and increment i. Otherwise we place Rj into the temporary array and increment j. We continue until we have examined every element in one or both partitions (if one partition still has elements in it, we can simply copy the rest over in order). This merge operation works because each subarray is sorted. Merge Sort is presented as Algorithm 12.8 with the Merge subroutine as Algorithm 12.9. Input : A (sub)collection A = {al, . . . , ar}, indices l, r Output : A collection A′ which is A sorted 1 if l < r then 2 m ←⌊l+r 2 ⌋ 3 L ←MergeSort(A, l, m) 4 R ←MergeSort(A, m + 1, r) 5 output Merge(L, R) 6 else 7 output A 8 end Algorithm 12.8: MergeSort 233
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 ←(j + 1) 13 end 14 k ←(k + 1) 15 end //At least one collection is empty, we can blindly copy the other 16 while i ≤n do 17 Ak ←Li 18 i ←(i + 1) 19 k ←(k + 1) 20 end 21 while j ≤m do 22 Ak ←Rj 23 j ←(j + 1) 24 k ←(k + 1) 25 end 26 output A Algorithm 12.9: Merge We present an example run of Merge Sort in Figure 12.10 (here, we have made the collection of size 8 to emphasize the even split). An example run of the Merge subroutine on the last merge operation of this algorithm is presented in Figure 12.11. 234
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 102 i j 2 4 4 k (c) Iteration Three. Again the element in the left partition is less. 4 4 9 42 2 12 34 102 i j 2 4 4 9 k (d) Iteration Four. And so on. 4 4 9 42 2 12 34 102 i j 2 4 4 9 12 k (e) Iteration Five 4 4 9 42 2 12 34 102 i j 2 4 4 9 12 34 k (f) Iteration Six 4 4 9 42 2 12 34 102 i j 2 4 4 9 12 34 42 k (g) Iteration Seven 4 4 9 42 2 12 34 102 j 2 4 4 9 12 34 42 102 k (h) Final Copy. After one sub-collection has been exhausted the rest (in this case only one) of the elements in the other are blindly copied over. Figure 12.11.: Demonstration of the merge operation in Merge Sort. Here we depict the final Merge subroutine invocation from the previous example. 236
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 complexity of n log (n). 12.2.5. Other Sorts There are dozens of other sorting algorithms and many more variations on sorting algorithms, each with some unique properties and advantages. For example, Heap Sort, due to J. W. J. Williams, 1964 [38], uses a data structure called a heap. A heap stores elements in a tree structure and offers efficient insertion of elements and retrieval of the minimal (or maximal for a “max-heap”) element. The sorting algorithm then simply inserts each element into the heap, and retrieves each element out of the heap. Because of the the heap data structure, elements come out of the heap in order. Other sorting algorithms are variations on those we’ve already seen or hybrid sorting algorithms. For example, we’ve already noted that Insertion Sort is efficient on “small” arrays. One common technique is to use a fast sorting algorithm such as Quick Sort or Merge Sort, but then switch over to Insertion Sort at some point in the recursion rather than recursing to the point that the collection is of size 1 (or 0). This switch point is usually tuned using empirical experiments. A more recent sorting algorithm is Tim Sort, due to Tim Peters in 2002 [34] who originally developed it as the default sorting algorithm for the Python language. It has since been adopted in Java (version 7 for arrays of non-primitive types). Tim Sort is a sort of “bottom-up” Merge Sort/Insertion Sort hybrid. Instead of recursing, it looks for subsequences of elements that are already in order or nearly in order, then merges them. It was designed to have many of the desirable properties of a sorting algorithm including stability (see Section 12.3.6). 12.2.6. Comparison & Summary To illustrate just how much more efficient an n log (n) sorting algorithm is over a naive n2 algorithm consider the same scenarios as with searching. Suppose we want to sort a huge collection of 1 trillion, 1012, elements. Doing so with Selection Sort or Insertion Sort would require about n2 = (1012)2 = 1024 237
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 elements and then want to double the size of our collection to 2n. How do each of these types of algorithms perform? For the slow, n2 algorithms we have (2n)2 = 4n2 Doubling the input size quadruples the number of operations Selection Sort and Insertion Sort perform. However, for Quick Sort and Merge Sort, we only have 2n log (2n) = 2n (log (2) + log (n)) = 2n log (n) + 2n That is, only about twice as many operations (with an additive term of 2n). Table 12.2 gives a summary of the complexity and other properties of the sorting algorithms we’ve seen. Algorithm Complexity Stable? Notes Best Average Worst Selection Sort ∼n2 ∼n2 ∼n2 No Insertion Sort ∼n ∼n2 ∼n2 Yes Best in practice for small collections Quick Sort ∼n log n ∼n log n ∼n2 No Performance depends on pivot choices Merge Sort ∼n log n ∼n log n ∼n log n Yes Requires extra space Table 12.2.: Summary of Sorting Algorithms. See Section 12.3.6 for a discussion on stability. 12.3. Searching & Sorting In Practice 12.3.1. Using Libraries and Comparators In practice you do not write your own searching and sorting algorithm implementations. Instead, you use the functionality provided by the language, a framework, or a library. First, there is rarely a good reason to “reinvent the wheel” and write your own if the functionality already exists. Second, the algorithms and code provided by a language or library are typically optimized and have been well-tested. Established libraries have 238
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 any type. The basic algorithms for searching and sorting are generic themselves (after all we presented them as pseudocode). The only real difference between an implementation for, say, numbers versus a sorting algorithm for strings is how pairs of elements are compared and ordered. This genericness extends to objects. It would be extremely inefficient, development-wise, to have to rewrite Quick Sort for a collection of student objects to sort them by name, then another to sort them by GPA, then another for ID, and repeat them all again for a reversed ordering. Instead, a single, generic sorting algorithm is implemented that can be configured by passing in a comparator. A comparator is a function or object that provides functionality to determine how to order two elements. In general, a comparator takes two arguments, a, b which are the elements to be compared and returns an integer value with the following “contract.” It returns: • something negative, < 0 if a comes before b, a < b • zero if a and b are equivalent, a = b • something positive, > 0 if a comes after b, a > b We’ve previously seen this type of functionality when comparing strings in Chapter 8. Using comparators allows us to reuse the generic search and sorting algorithms. Now for each sorting that we want, we only need to create a comparator to define the ordering rather than reimplementing the whole algorithm every single time. This relationship is depicted in Figure 12.12. 12.3.2. Preventing Arithmetic Errors Recall that in binary search, we need to compute the index of the middle element.9 Given a left l and right r index variable, we computed the middle index as m ← l + r 2  Though mathematically correct, when implementing an expression like this, care must be taken. We may initially translate this pseudocode into a line that looks something like the following. 9Some implementations of Quick Sort will do something similar when choosing the “middle” element as a pivot. 239
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 that does know how to order elements. By using a comparator, the sorting function can be kept general and generic so that one implementation can be used for any type of data. int middle_index = (left + right) / 2; However, this is prone to arithmetic errors in certain situations, particularly when dealing with large arrays. If the variables left and right have a sum that exceeds the maximum value that a signed 32-bit integer can hold (231 −1 = 2, 147, 483, 647), then overflow will occur before the division by 2, leading to a (potentially) negative index value and thus an invalid out-of-bounds error or exception. One solution would be to use a variable type that supports larger values. For example, a 64-bit signed integer would be able to handle arrays of 9.223 quintillion elements. However, depending on the language, you may not be able to use such variable types as index values. Another solution is to use operations that do not introduce this potential for overflow. For example, l + r 2 = l + (r −l) 2 but the expression on the right hand side will not be prone to overflow. Thus the code, int middle_index = left + (right - left) / 2; would be safer to use. In fact, this bug is quite common [32] and was in the Java implementation of binary search, unreported for nearly a decade [10]. 240
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 following. 1 if a < b then 2 output −1 3 else if a = b then 4 output 0 5 else 6 output +1 7 end For example, if a = 5 and b = 10 then our comparator would output −1. If the values were a = 10, b = 5 it would output +1, and if they were equal, a = b = 10 then it would output zero. A common “trick” is to instead compute the difference between these values, a −b. Observe: a b a −b 5 10 −5 10 5 5 5 5 0 The sign of the difference in each of these examples matches the logic of our if-else-if statement. The lazy programmer may be tempted to write a one liner, “output (a −b)” instead of the if-else-if statement. However, this would fail for certain values of a and b. Suppose both of them are 32-bit 2s complement integers. And suppose that a = 231 −1, the maximum representable value, and b = −10. In the logic above, b would come before a and so we would expect a positive result. However, our arithmetic trick would give the following result: (231 −1) −(−10) = 231 + 9 which, mathematically, is positive, but exceeds the maximum representable value, leading to overflow. In most systems, the result of this arithmetic is −2, 147, 483, 639, a negative value. There are many other input values that could cause arithmetic overflow. Only if you are absolutely sure that no arithmetic overflow is possible should you even consider using this “trick.” Another issue with this trick is when comparing floating point values. GPAs for example: suppose that a = 4.0 and b = 3.9. Their difference would be a −b = 0.1. However, a comparator returns an integer value. In some languages this result would be casted to 241
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 provide a total order. For example, suppose we have students “Gary Busey” with an ID of 1234 and another student with the same name, “Gary Busey” but with an ID of 4321. It is entirely possible (and common) for different people to have the same names. However, a comparator that ordered student objects based only on the name fields would interpret these as the same person. The distinction is especially important when using a comparator in a sorted collection (such as a Binary Search Tree, or Ordered Hash Map data structure) that maintains an ordering on the elements. Many of these data structures do not allow “duplicate” elements where duplication is determined by the comparator. Attempting to insert both of these students will likely result in only one of them being in the collection as the second will be interpreted as a a duplicate. In such scenarios it is important to design your comparator to break ties by using some unique data field of an object such as an ID. 12.3.5. Artificial Ordering Many languages recognize what is called a “natural ordering” on certain elements. For example, numbers have a natural ordering: from least to greatest. Strings also have a natural ordering: lexicographic ordering. However, we often wish to order elements in an artificial ordering. For example, suppose we wish to include the year of a student, Freshman, Sophomore, Junior, or Senior. If we modeled these as strings, the natural ordering would be alphabetical: Freshman, Junior, Senior, Sophomore However, if we order students by year, we would want the artificial order of Freshman, Sophomore, Junior, or Senior. To do this, we might have a whole series of if-else-if statements to order these elements 242
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 solution if we want to then add support for “Pre-freshman” or “Graduate”, etc. Another solution would be to model the year using a data type that has a natural ordering. For example, we could define an enumerated type and associate each of the years with 0, 1, 2, 3; giving them a natural ordering. Alternatively, we could use a data structure, such as a map, to model the artificial ordering. For example, we could map “Freshman” to 0, “Sophomore” to 1, etc. Then, when we wanted to order two elements, we could look up the “natural value” via the map and use their natural ordering to order our elements. 12.3.6. Sorting Stability One desirable property of sorting algorithms is stability. A sorting algorithm is stable if the relative order of “equal” elements is preserved. For example, suppose we have the following integer values: 10, 2a, 5, 2b The subscripts on the two 2 values are for demonstration purposes only. A stable sorting algorithm would sort the elements as: 2a, 2b, 5, 10 preserving the relative ordering of the two 2 elements. The element 2a came before 2b prior to sorting and remains so after sorting. However, an unstable sorting algorithm may instead produce 2b, 2a, 5, 10 The collection is still sorted, but the two equal elements have been reversed from their original ordering. 243
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 GPA (because the first ordering would be preserved). An unstable sorting algorithm would result in all Freshman being grouped together, but within that grouping, the students would not necessarily be ordered by GPA. As indicated in Table 12.2, some algorithms (as presented) are stable and others are not. For example, Selection Sort is not stable. Consider the following input: 2a, 2b, 1, 5 In the first iteration, 1 and 2a would be swapped, resulting in a sorted collection and no further swaps, but with 2b preceding 2a. Insertion Sort, however, is stable: it only moves an element down the collection if it is strictly less than its adjacent element. Likewise, Merge Sort is stable since we “prefer” elements from the left partition when equal. Quick Sort is not stable as the partitioning can easily place things out of their original relative ordering. Usually, sorting algorithms can be made to be stable by doing some extra work, but it may impact the performance. 12.4. Exercises Exercise 12.1. Give an input example input demonstrating that the Quick Sort al- gorithm, as presented, is unstable. Run through the algorithm to demonstrate how it results in an unstable sort. Exercise 12.2. Implement the sorting algorithms described in this chapter in the programming language of your choice. Then setup experiments: run each on randomly ordered collections many times to get an average run time. Graph these empirical results and see if they match the theoretical results of our analysis. Be sure to also include any built-in sorting functionality your language provides as a benchmark. Exercise 12.3. Ternary search is similar to binary search in that it searches a sorted array. However, instead of splitting the array in two, it splits it into three partitions and makes two comparisons to determine which third the element lies in (if it is in the collection). Implement ternary search and benchmark it against a binary search implementation. Exercise 12.4. Data has a “natural” ordering: numbers are ordered in nondecreasing order, strings are ordered lexicographically (according to the ASCII text table). However, in many situations, the natural ordering isn’t the expected ordering. For example, class 244
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 them according to an alternative ordering of the English alphabet. As an example, one possible ordering would be: n e d c r h a l g k m z f w j o b v x q y i p u s t Your job will be to sort a list of English language words using this artificial ordering of the English alphabet. Specifically, you will read in an input file in the following format. The first line is the new ordering of English letters, each separated by a space. Each line after that contains a single string. You will read in this file, process it and produce a reordered list of the words sorted according to the new ordering. An example input: n e d c r h a l g k m z f w j o b v x q y i p u s t vcawufotrb laencfuesw gvtkwekfom vrsfqictqc wmcvmjmtet qetegyqelu newaxdtjlt nfrfrwkknj fzqrvgblov gkkmgwwwpa The result ordering: Artificial Ordering: newaxdtjlt nfrfrwkknj laencfuesw gkkmgwwwpa gvtkwekfom fzqrvgblov wmcvmjmtet vcawufotrb vrsfqictqc 245
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” should come before “newaxn” in the ordering above. Exercise 12.5. Write comparators for all the member fields of the album object in Exercise 10.2. Exercise 12.6. Write comparators for all the member fields of the savings account object in Exercise 10.3. Exercise 12.7. Write comparators for all the member fields of the stadium object in Exercise 10.4. Exercise 12.8. Write comparators for all the member fields of the network device object in Exercise 10.5. Exercise 12.9. Write comparators for all the member fields of the airport object in Exercise 10.6. 246
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, microcontrollers, and supercomputers. It is generally an “imperative” language which is a paradigm that characterizes computation in terms of executable statements and functions that change a program’s state (variable values). C has been highly influential in the design and syntax of other languages including C++, Objective-C, C#, Java, and PHP, among many others. Many languages have adopted the basic syntactic elements and structured programming approach of the C language. C was originally developed by Dennis Ritchie while at AT&T Bell Labs 1969–1972. C was born out of the need for a new language for the PDP-11 minicomputer that used the Unix operating system (written by Ken Thompson). From its inception, C has had a close relation to Unix; in fact the operating system was subsequently rewritten in C, making it the first OS to be written in a language other than assembly. The language was dubbed “C” as its predecessor was named “B,” a simplified version of BCPL (Basic Combined Programming Language). The first formal specification was published as The C Programming Language by Kernighan and Ritchie (1978) [26] often referred to as “The K&R Book” which would later become the American National Standards Institute (ANSI) C standard. C gained in popularity and directly influenced object-oriented variations of it. Bjarne Stroustrup developed C++ while at Bell Labs from 1979–1983. Brad Cox and Tom Love developed Objective-C from 1981–1983 at their company Stepstone. Subsequent standards of the C language have added and extended features. In 1990, the International Organization for Standardization (ISO)/IEC 9899:1990 standard, referred to as C89 or C90, was adopted. About every 10 years since, a new standard has been adopted; ISO/IEC 9899:1999 (referred to as C99) in 1999 and ISO/IEC 9899:2011 (C11) in 2011. 15.1. Getting Started: Hello World The hallmark of an introduction to a new programming language is the Hello World! program. It consists of a simple program whose only purpose is to print out the message 253
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 some manner. The simplicity of the program allows the focus to be on the basic syntax of the language. It is also typically used to ensure that your development environment, compiler, runtime environment, etc. are functioning properly with a Minimum Working Example (MWE). The Hello World! program is generally attributed to Brian Kernighan who used it as an example of programming in C in 1974 [25]. A basic Hello World! program in C can be found in Code Sample 15.1. We will not focus on any particular development environment, code editor, or any particular operating system, compiler, or ancillary standards in our presentation. However, as a first step, you should be able to write, compile, and run the above program on the environment you intend to use for the rest of this book. This may require that you download and install a basic C compiler/development environment (such as GCC, the GNU Compiler Collection on OSX/Unix/Linux, cygwin or MinGW for Windows) or a full IDE (such as Xcode for OSX, or Code::Blocks, http://www.codeblocks.org/ for Windows). 15.2. Basic Elements Using the Hello World! program as a starting point, we will now examine the basic elements of the C language. 254
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 language so variables must be declared along with their types before using them. • Strings are delimited with double quotes. Single characters, including special escaped characters are delimited by single quotes; "this is a string" , and these are characters: 'A' , '4' , '$' and '\n' • Executable statements are terminated by a semicolon, ; • Code blocks are defined by using opening and closing curly brackets, { ... } . Moreover, code blocks can be nested: code blocks can be defined within other code blocks. • Variables are scoped to the code block in which they are declared and are only valid within that code block. • In general, whitespace between coding elements is ignored. Though not a syntactic requirement, the proper use of whitespace is important for good, readable code. Code inside code blocks is indented at the same indentation level. Nested code blocks are indented further. Think of a typical table of contents or the outline of a formal paper or essay. Sections and subsections or points and subpoints all follow proper indentation with elements at the same level at the same indentation. This convention is used to organize code and make it more readable. 15.2.2. Preprocessor Directives The lines, 1 #include <stdlib.h> 2 #include <stdio.h> are preprocessor directives. Preprocessor directives are instructions to the compiler to modify the source code before it starts to compile it. These particular lines are “including” standard libraries of functions so that the program can use functionality that has already 255
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 standard ( std ) input/output ( io ) library which contains basic input/output (I/O) functions that we can use. In particular, the standard output function printf() is part of this library. Failure to include a library means that you will not be able to use the functions it provides in your program. Using the functions without including the library may result in a compiler error. The .h in the library names stands for “header”; function declarations are typically contained in a header file while their definitions are placed in a source file of the same name. We’ll explore this convention in detail when we look at functions in C (Chapter 18). There are many other important standard libraries that we’ll touch on as needed; of immediate interest is the standard mathematics library, math.h . It includes many useful functions to compute common mathematical functions such as the square root and natural logarithm. Table 15.1 highlights several of these functions. To use them you’d include the math library in your source file #include <math.h> and then “call” them by providing input and assigning the output value to a variable. For example: 1 double x = 1.5; 2 double y, z; 3 y = sqrt(x); //y now has the value √x = √ 1.5 4 z = sin(x); //z now has the value sin (x) = sin (1.5) In both of the function calls above, the value of the variable x is “passed” to the math function which computes and “returns” the result which then gets assigned to another variable. Macros Another preprocessor directive establishes macros using the #define keyword. A macro is a single instruction that specifies a more complex set of instructions. The macro can be used to define constants to be used throughout your program. To illustrate, consider the following example. 256
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.71828 . . . log(x) Natural logarithm, ln (x)c log10(x) Logarithm base 10, log10 (x)c pow(x,y) The power function, computes xy sqrt(x) Square root functionc Table 15.1.: Several functions defined in the C standard math library. aThe absolute value function is actually in the standard library, stdlib.h . ball trigonometric functions assume input is in radians, not degrees. cInput is assumed to be positive, x > 0. 257
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_PER_KM throughout our program instead of magic numbers whose meaning and intent may not be immediately clear. Moreover, if we want to change the definition (say make it more precise, using 1.60934 instead) then we only need to change the macro instead of making the same change throughout our program. As a stylistic note: macro constants in C are usually associated with uppercase underscore casing as in our example. Also, the math standard library defines several macros for common mathematical constants such as π, e, and √ 2 ( M_PI , M_E , and M_SQRT2 respectively) among others. 15.2.3. Comments Comments can be written in a C program either as a single line using two forward slashes, //comment or as a multiline comment using a combination of forward slash and asterisk: /* comment */ . With a single line comment, everything on the line after the forward slashes is ignored. With a multiline comment, everything between the forward slash/asterisk is ignored. Comments are ultimately ignored by the compiler so the amount of comments do not have an effect on the final executable code. Consider the following example. 1 //this is a single line comment 2 int x; //this is also a single line comment, but after some code 3 4 /* 5 This is a comment that can 6 span multiple lines to format the comment 7 message more clearly 8 */ 9 double y; Most code editors and IDEs will present comments in a special color or font to distinguish them from the rest of the code (just as our example above does). Failure to close a 258
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 executable and the program is invoked, the code in the main() function starts executing. In our example, the code between the two curly brackets defines the main() function. At the end of the function we have a return statement. We’ll examine return statements in detail when we examine functions. The program is “returning” a zero value to the operating system. The convention in C is that zero indicates “no error occurred” while a non-zero value is used to indicate that “some” error occurred (the value used is determined by system standards such as the Portable Operating System Interface (POSIX) standard). In addition, our main() function has two arguments: argc and argv which serve to communicate any command line arguments provided to the program (review Section 2.4.4 for details). The first, argc is an integer that indicates the number of arguments provided including the executable file name itself. The second, argv actually stores the arguments as strings. We will understand the syntax later on, but for now we can at least understand how we might convert these arguments to different types such as integers and floating point numbers. Recall that argv is the argument vector: it is an array (see Chapter 20) of the command line arguments. To access them, you can index them starting at zero, the first being argv[0] , the second argv[1] , etc. (the last one of course would be at argv[argc-1] ). The first one is always the name of the executable file being run. The remaining are the command line arguments provided by the user. To convert them you can use two different functions, atoi() and atof() which are short for alphanumeric to integer and floafing-point number respectively. An example: 1 //prints the first command line argument: 2 printf("%s\n", argv[0]); 3 //converts the "second" command line argument to an integer 4 int x = atoi(argv[1]); 5 //converts the "third" command line argument to a double: 6 double y = atof(argv[2]); 259
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 on most modern systems.1 With a 32-bit signed int we can represent integers in the range −2, 147, 483, 648 to 2,147,483,647. Doubles ( double ) types are double-precision floating point numbers as per the IEEE 754 standard and provide about 16 digits of precision. C provides a float (single precision floating point number) type and there are various modifiers such as short , long , unsigned and signed that can be used, but these are either system-dependent or rely on later versions of the C standard (such as C99). We will restrict our focus to more portable, interoperable code and stick with the basic int and double types in our code. Finally, the char type is typically a single byte that represents a single ASCII character. For all intents and purposes a char can be treated as an integer in the range 0 to 127 (or 255) as defined by the ASCII text table (see Table 2.4). 15.3.1. Declaration & Assignment C is a statically typed language meaning that all variables must be declared before you can use them or refer to them. In addition, when declaring a variable, you must specify both its type and its identifier. For example: 1 int numUnits; 2 double costPerUnit; 3 char firstInitial; Each declaration specifies the variable’s type followed by the identifier and ending with a semicolon. The identifier rules are fairly standard: a name can consist of lower and uppercase alphabetic characters, numbers, and underscores but may not begin with a numeric character. We adopt the modern camelCasing naming convention for variables in our code. The assignment operator is a single equal sign, = and is a right-to-left assignment. The 1You may have to deal with 16-bit int types in legacy systems/compilers or in modern embedded systems. 260
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 understand and to keep in mind is: if you declare a variable but do not assign it a value, its value is undefined. If we code something like int a; , the value of the variable a is not necessarily zero; depending on the system, it could contain a special value that indicates “uninitialized memory” or it could contain garbage, or it could have the value zero. The C standard does not specify default values for variables. The default value of variables is highly system dependent–on the compiler, the libraries, and even the operating system. You should not make any assumptions on the initial or default values of variables. If you need such assumptions, then values must be assigned. For brevity, C allows you to declare a variable and immediately assign it a value on the same line. Our example could be written more compactly written as follows. 1 int numUnits = 42; 2 double costPerUnit = 32.79; 3 char firstInitial = 'C'; As another shorthand, we can declare multiple variables on the same line by delimiting them with a comma. However, they must be of the same type. We can also use an assignment with them. 1 int numOrders, numUnits = 42, numCustomers = 10, numItems; 2 double costPerUnit = 32.79, salesTaxRate; Another convenient keyword is const , short for “constant.” We can apply it to any variable to indicate that it is a read-only variable. Of course, we must assign it a value at declaration. For example: 261
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 of these operators is a binary operator that acts on two operands which can be literals, variables or expressions and follow the usual rules of arithmetic when it comes to order of precedence (multiplication and division before addition and subtraction). 1 int a = 10, b = 20, c = 30, d; 2 d = a + 5; 3 d = a + b; 4 d = a - b; 5 d = a + b * c; 6 d = a * b; 7 d = a / b; //integer division and truncation! See below 8 9 double x = 1.5, y = 3.4, z = 10.5, w; 10 w = x + 5.0; 11 w = x + y; 12 w = x - y; 13 w = x + y * z; 14 w = x * y; 15 w = x / y; 16 17 //you can do arithmetic with both types: 18 w = a + x; 19 d = b + y; //truncation also occurs here! Special care must be taken when dealing with int types. For all four operators, if both operands are integers, the result will be an integer. For addition, subtraction, and multiplication this isn’t a big deal, but for division it means that when we divide, say 262
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 floating point number to an integer also results in truncation because an int type cannot handle the fractional part. In the line d = b + y above, b + y correctly evaluates as 20 + 3.4 = 23.4, but when assigned to the int variable d the .4 gets truncated and d is assigned the value 23. Assigning an int value to a double variable is not a problem as the integer 2 implicitly becomes the floating point number 2.0. A solution to this problem is to use explicit type casting to force at least one of the operands in an integer division to become a double type. For example: 1 int a = 10, b = 20; 2 double x; 3 4 x = (double) a / b; results in x getting the “correct” value of 0.5. This works because the (double) code forces the int variable a to temporarily be treated as a double variable (in this case 10.0) for the purposes of division (so that truncation does not occur). C also supports the integer remainder operator using the % symbol. This operator gives the remainder of the result of dividing two integers. Examples: 1 int x; 2 3 x = 10 % 5; //x is 0 4 x = 10 % 3; //x is 1 5 x = 29 % 5; //x is 4 15.5. Basic I/O The standard I/O library ( stdio.h ) contains many functions that facilitate input and output including printf() for standard output and scanf() (scan formatted input) 263
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 prompts the user for an input. The scanf() then executes and the program waits for the user to enter input. The user is free to start typing. When the user is done, they hit the enter key at which point the program resumes and reads the input from the standard input buffer, converts the value entered by the user into an integer and places the result in the variable a where it can now be used by the remainder of the program. A few points of interest. First, the same placeholder as printf() was used, %d for int values. However, when we “passed” the variable a to scanf() we placed an ampersand, & in front of it. This is passing the variable by reference and we’ll explore that concept further in Chapter 18, but for now just know that when using variables with scanf() , an ampersand is required. Failure to place an ampersand in front of a variable with scanf() will likely result in a segmentation fault (an illegal memory access). You can use the same placeholder, %c with scanf() to read in a single character as well. However, for floating point numbers, in particular double types, the placeholder %lf must be used (which stands for long float, a double precision number). Failure to use the correct placeholder may result in garbage results as the input will be interpreted incorrectly. Another example: 1 double x; 2 printf("Please enter a fractional number: "); 3 scanf("%lf", &x); Another potential problem is that scanf() expects a certain format (thus its name). If we prompt the user for a number but they just start mashing the keyboard giving non-numerical input, we may get incorrect results. scanf() will interpret the input as zero. It may be very difficult to distinguish between the case of a user actually entering 264
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 degrees Fahrenheit and convert it to degrees Celsius using the formula C = (F −32) · 5 9 We begin with the basic program outline which will include preprocessor directives to bring in the standard library and the standard input/output library (we’ll need to prompt for input and print the result as output to the user). Further, we want our program to be executable, so we need to put our code into the main() function. Finally, we’ll document our program to indicate its purpose. 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 //TODO: implement this 11 12 return 0; 13 } It is common for programmers to use a comment along with a TODO note to themselves as a reminder of things that they still need to implement in a program. Let’s first outline the basic steps that our program will go through: 1. We’ll first prompt the user for input, asking them for a temperature in Fahrenheit 265
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 outline of such a program directly in the code using comments to provide a step-by-step process. For example: 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 //TODO: implement this 11 //1. Prompt the user for input in Fahrenheit 12 //2. Read the Fahrenheit value from the standard input 13 //3. Compute the degrees Celsius 14 //4. Print the result to the user 15 16 return 0; 17 } As we read each step it becomes apparent that we’ll need a couple of variables: one to hold the Fahrenheit (input) value and one for the Celsius (output) value. It also makes sense that each of these should be double variables as we want to support fractional values. So at the top of our main() function, we’ll add the variable declarations: double fahrenheit, celsius; Each of the steps is now straightforward; we’ll use a printf() statement in the first step to prompt the user for input: printf("Please enter degrees in Fahrenheit: "); In the second step, we’ll use the standard input to read the fahrenheit variable value from the user. Recall that we use the placeholder %lf for reading double values and 266
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 running the program as defined above and you’ll find that you don’t get correct answers. In fact, you’ll find that no matter what values you enter, you get zero. This is because of the calculation using 5 / 9 : recall what happens with integer division: truncation! This will always end up being zero. One way we could fix it would be to pull out our calculators and find that 5 9 = 0.55555 . . . and replace 5/9 with 0.555555 . But, how many fives? It may be difficult to tell how accurate we can make this floating point number by hardcoding it ourselves. A much better approach would be to let the compiler take care of the optimal computation for us by making at least one of the numbers a double to prevent integer truncation. That is, we should instead use 5.0 / 9 . The full program can be found in Code Sample 15.2. 15.6.2. Computing Quadratic Roots Some programs require the user to enter multiple inputs. The prompt-input process can be repeated. In this example, consider asking the user for the coefficients, a, b, c to a quadratic polynomial, ax2 + bx + c and computing its roots using the quadratic formula, x = −b ± √ b2 −4ac 2a As before, we can create a basic program with a main() function and start filling in the details. In particular, we’ll need to prompt for the input a, then read it in; then prompt for b, read it in and repeat for c. We’ll also need several variables: three for the coefficients a, b, c and two more; one for each root. Thus, we have 1 double a, b, c, root1, root2; 2 3 printf("Please enter a: "); 4 scanf("%lf", &a); 267
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 the Fahrenheit value from the standard input 16 scanf("%lf", &fahrenheit); 17 18 //3. Compute the degrees Celsius 19 celsius = (fahrenheit - 32) * 5.0/9; 20 21 //4. Print the result to the user 22 printf("%f Fahrenheit is %f Celsius\n", fahrenheit, celsius); 23 24 return 0; 25 } Code Sample 15.2.: Fahrenheit-to-Celsius Conversion Program in C 5 printf("Please enter b: "); 6 scanf("%lf", &b); 7 printf("Please enter c: "); 8 scanf("%lf", &c); Now to compute the roots: we need to take care that we correctly adapt the formula so it accurately reflects the order of operations. We also need to use the standard math library’s square root function (unless you want to write your own!2 Carefully adapting 2We will write several square root methods as exercises later! 268
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 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 printf("Please enter a: "); 14 scanf("%lf", &a); 15 printf("Please enter b: "); 16 scanf("%lf", &b); 17 printf("Please enter c: "); 18 scanf("%lf", &c); 19 20 root1 = (-b + sqrt(b*b - 4*a*c) ) / (2*a); 21 root2 = (-b - sqrt(b*b - 4*a*c) ) / (2*a); 22 23 printf("The roots of %fx^2 + %fx + %f are: \n", a, b, c); 24 printf(" root1 = %f\n", root1); 25 printf(" root2 = %f\n", root2); 26 return 0; 27 } Code Sample 15.3.: Quadratic Roots Program in C This program was interactive. As an alternative, we could have read all three of the 269
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: • What if the user entered zero for a? • What if the user entered some combination such that b2 < 4ac? • What if the user entered non-numeric values? • For the command line argument version, what if the user provided less than three arguments? Or more? How might we prevent the consequences of such bad inputs? How might we handle the event that a user enters bad input and how do we communicate these errors to the user? To begin to resolve these issues, we’ll need conditionals. 270
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 to be understood. 16.1. Logical Operators C has no built-in Boolean type, nor does it have any keywords associated with true and false. Instead, C uses numeric types as implicit Boolean types with the convention that zero is associated with false and any non-zero value is associated with true. So the values 1, 2.5, and even negatives, −1, −123.2421, etc. are all interpreted as true when used in logical statements. The standard numeric comparison operators are also supported. Consider the following code snippet: 1 int a = 10; 2 int b = 20; 3 int c = 10; 4 int d = 0; The six standard comparison operators are presented in Table 16.1 using these variables as examples. The comparison operators are the same when used with double types as well and int types can be compared with each other without type casting. The three basic logical operators are also supported as described in Table 16.2 using the same code snippet variable values as examples. 271
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 true Strictly Greater Than > a > 15 false a > 5 true a > b false a > c false Greater Than Or Equal To >= a >= 15 false a >= 5 true a >= b false a >= c true Table 16.1.: Comparison Operators in C Operator Operator Syntax Examples Values Negation ! !a false !d true And && a && b true a && d false Or || a || b true !a || d false Table 16.2.: Logical Operators in C 272
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-to-right logical And || left-to-right logical Or Lowest = , += , -= , *= , /= right-to-left assignment and compound assign- ment operators Table 16.3.: Operator Order of Precedence in C. Operators on the same level have equivalent order and are performed in the associative order specified. 16.1.1. Order of Precedence At this point it is worth summarizing the order of precedence of all the operators that we’ve seen so far including assignment, arithmetic, comparison, and logical. Since all of these operators could be used in one statement, for example, (b*b < 4*a*c || a == 0 || argc != 4) it is important to understand the order in which each one gets evaluated. Table 16.3 summarizes the order of precedence for the operators seen so far. This is not an exhaustive list of C operators. 16.1.2. Comparing Strings and Characters The comparison operators in Table 16.1 can also be used for single characters because of the nature of the ASCII text table (see Table 2.4). Each alphanumeric character, including the various symbols and whitespace characters, is associated with an integer 0– 127. We can therefore write statements like ('A' < 'a') , which is true since uppercase letters are ordered before lowercase letters in the ASCII table ( 'A' is 65 and 'a' is 97 and so 65 < 97 is true). Several more examples can be found in Table 16.4. Numeric comparison operators cannot be used to compare strings in C. For example, we could write ("aardvark" < "zebra") which would be valid C, and it would even have a result. However, that result wouldn’t necessarily be true or false. The reason for this is that strings in C are actually represented as arrays, which in turn are represented as memory locations. We’ll explore these issues in greater depth later on, but for now 273
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. If, If-Else, If-Else-If Statements Conditional statements in C utilize the keywords if , else , and else if . Condi- tions are placed inside parentheses immediately after the if and else if keywords. Examples of all three can be found in Code Sample 16.1. Some observations about the syntax: the statement, if(x < 10) does not have a semicolon at the end. This is because it is a conditional statement that determines the flow of control and not an executable statement. Therefore, no semicolon is used. Suppose we made a mistake and did include a semicolon: 1 int x = 15; 2 if(x < 10); { 3 printf("x is less than 10\n"); 4 } Some compilers may give a warning, but this is valid C; it will compile and it will run. However, it will end up printing x is less than 10 , even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this case, we’ve provided an empty executable statement ended by the semicolon. The code is essentially equivalent to 1 int x = 15; 2 if(x < 10) { 3 } 274
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) { 15 printf("x is less than 10\n"); 16 } else if(x == 10) { 17 printf("x is equal to ten\n"); 18 } else { 19 printf("x is greater than 10\n"); 20 } Code Sample 16.1.: Examples of Conditional Statements in C 275
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 regardless of the value of x. Another convention that we’ve used in our code is where we have placed the curly brackets. First, if a conditional statement is bound to only one statement, the curly brackets are not necessary. However, it is best practice to include them even if they are not necessary and we’ll follow this convention. Second, the opening curly bracket is on the same line as the conditional statement while the closing curly bracket is indented to the same level as the start of the conditional statement. Moreover, the code inside the code block is indented. If there were more statements in the block, they would have all been at the same indentation level. 16.3. Examples 16.3.1. Computing a Logarithm The logarithm of x is the exponent that some base must be raised to get x. The most common logarithm is the natural logarithm, ln (x) which is base e = 2.71828 . . .. But logarithms can be in any base b > 1.1 What if we wanted to compute log2 (x)? Or logπ (x)? Let’s write a program that will prompt the user for a number x and a base b and computes logb (x). Arbitrary bases can be computed using the change of base formula: logb(x) = loga (x) loga (b) If we can compute some base a, then we can compute any base b. Fortunately we have such a solution. Recall that the standard library provides a function to compute the natural logarithm, log() ). This is one of the fundamentals of problems solving: if a solution already exists, use it. In this case, a solution exists for a different, but similar problem (computing the natural logarithm), but we can adapt the solution using the change of base formula. In particular, if we have variables b (base) and x , we can compute logb (x) using 1Bases can also be 0 < b < 1, but we’ll restrict our attention to increasing functions only. 276
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 we have read in the input from the user we can make a check for good input using an if statement. 1 if(x <= 0 || b <= 1) { 2 printf("Error: bad input!\n"); 3 exit(1); 4 } This code has something new: exit(1) . The exit() function immediately terminates the program regardless of the rest of the code that it may remain. The argument passed to exit is an integer that represents an error code. The convention is that zero indicates “no error” while non-zero values indicate some error. This is a simple way of performing error handling: if the user provides bad input, we inform them and quit the program, forcing them to run it again and provide good input. By prematurely terminating the program we avoid any illegal operation that would give a bad result. Alternatively, we could have split the conditions into two statements and given more descriptive error messages. We use this design in the full program which can be found in Code Sample 16.2. The program also takes the input as command line arguments. Now that we have conditionals, we can actually check that the correct number of arguments was provided by the user and quit in the event that they don’t provide the correct number. 16.3.2. Life & Taxes Let’s adapt the conditional statements we developed in Section 3.6.4 into a full C program. The first thing we need to do is establish the variables we’ll need and read them in from the user. At the same time we can check for bad input (negative values) for both the inputs. 1 double income, baseTax, numChildren, credit, totalTax; 2 3 printf("Please enter your Adjusted Gross Income: "); 4 scanf("%lf", &income); 5 277
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 upper bounds just as in the original example. 1 if(income <= 18150) { 2 baseTax = income * .10; 3 } else if(income <= 73800) { 4 baseTax = 1815 + (income - 18150) * .15; 5 } else if(income <= 148850) { 6 ... 7 } else { 8 baseTax = 127962.50 + (income - 457600) * .396; 9 } Next we compute the child tax credit, taking care that it does not exceed $3,000. A conditional based on the number of children suffices as at this point in the program we already know it is zero or greater. 1 if(numChildren <= 3) { 2 credit = numChildren * 1000; 3 } else { 4 credit = 3000; 5 } Finally, we need to ensure that the credit does not exceed the total tax liability (the credit is non-refundable, so if the credit is greater, the tax should only be zero, not negative). 278
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 quadratic polynomial by reading coefficients a, b, c in from the user. One of the problems we had previously identified is if the user enters “bad” input: if a = 0, we would end up dividing by zero; if b2 −4ac < 0 then we would have complex roots. With conditionals, we can now check for these issues and exit with an error message. Another potential case we might want to handle differently is when there is only one distinct root (b2 −4ac = 0). In that case, the quadratic formula simplifies to −b 2a and we can print a different, more specific message to the user. The full program can be found in Code Sample 16.4. 279
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 b = atof(argv[1]); 18 x = atof(argv[2]); 19 20 if(x <= 0) { 21 printf("Error: x must be greater than zero\n"); 22 exit(1); 23 } 24 if(b <= 1) { 25 printf("Error: base must be greater than one\n"); 26 exit(1); 27 } 28 29 result = log(x) / log(b); 30 printf("log_(%f)(%f) = %f\n", b, x, result); 31 return 0; 32 } Code Sample 16.2.: Logarithm Calculator Program in C 280
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("How many children do you have?"); 15 scanf("%d", &numChildren); 16 17 if(income < 0 || numChildren < 0) { 18 printf("Invalid inputs"); 19 exit(1); 20 } 21 22 if(income <= 18150) { 23 baseTax = income * .10; 24 } else if(income <= 73800) { 25 baseTax = 1815 + (income -18150) * .15; 26 } else if(income <= 148850) { 27 baseTax = 10162.50 + (income - 73800) * .25; 28 } else if(income <= 225850) { 29 baseTax = 28925.00 + (income - 148850) * .28; 30 } else if(income <= 405100) { 31 baseTax = 50765.00 + (income - 225850) * .33; 32 } else if(income <= 457600) { 33 baseTax = 109587.50 + (income - 405100) * .35; 34 } else { 35 baseTax = 127962.50 + (income - 457600) * .396; 36 } 37 38 if(numChildren <= 3) { 39 credit = numChildren * 1000; 40 } else { 41 credit = 3000; 42 } 43 44 if(baseTax - credit >= 0) { 45 totalTax = baseTax - credit; 46 } else { 47 totalTax = 0; 48 } 49 50 printf("AGI: $%10.2f\n", income); 51 printf("Tax: $%10.2f\n", baseTax); 52 printf("Credit: $%10.2f\n", credit); 53 printf("Tax Liability: $%10.2f\n", totalTax); 54 55 return 0; 56 } Code Sample 16.3.: Tax Program in C 281
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]); 15 exit(1); 16 } 17 18 a = atof(argv[1]); 19 b = atof(argv[2]); 20 c = atof(argv[3]); 21 22 if(a == 0) { 23 printf("Error: a cannot be zero\n"); 24 exit(1); 25 } else if(b*b < 4*a*c) { 26 printf("Error: cannot handle complex roots\n"); 27 exit(1); 28 } else if(b*b == 4*a*c) { 29 root1 = -b / (2*a); 30 printf("Only one distinct root: %f\n", root1); 31 } else { 32 root1 = (-b + sqrt(b*b - 4*a*c) ) / (2*a); 33 root2 = (-b - sqrt(b*b - 4*a*c) ) / (2*a); 34 35 printf("The roots of %fx^2 + %fx + %f are: \n", a, b, c); 36 printf(" root1 = %f\n", root1); 37 printf(" root2 = %f\n", root2); 38 } 39 return 0; 40 } Code Sample 16.4.: Quadratic Roots Program in C With Error Checking 282
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 contains an example of a basic while loop in C. Just as with conditional statements, our code styling places the opening curly bracket on the same line as the while keyword and continuation condition. The inner block of code is also indented and all lines in the block are indented to the same level. In addition, the continuation condition does not contain a semicolon since it is not an executable statement. Just as with an if-statement, if we had placed a semicolon it would have led to unintended results. Consider the following: 1 while(i <= 10); { 2 //perform some action 3 i++; //iteration 4 } 1 int i = 1; //Initialization 2 while(i <= 10) { //continuation condition 3 //perform some action 4 i++; //iteration 5 } Code Sample 17.1.: While Loop in C 283
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 consequence of the semicolon, the executable statement that gets bound to the while loop is empty. What happens is even worse: the program will enter an infinite loop. To see this, the code is essentially equivalent to the following: 1 while(i <= 10) { 2 } 3 { 4 //perform some action 5 i++; //iteration 6 } In the while loop, we never increment the counter variable i , the loop does nothing, and so the computation will continue on forever! Some compilers may warn you about this, others will not. It is valid C and it will compile and run, but obviously won’t work as intended. Avoid this problem by using proper syntax and good style. Another common use case for a while loop is a flag-controlled loop in which we use a Boolean flag rather than an expression to determine if a loop should continue or not. Recall that in C, zero is treated as false and any non-zero numeric value is treated as true. We can thus create an implicit Boolean flag by using an integer variable and setting it to 1 for true and 0 for false (when we want the loop to terminate). An example can be found in Code Sample 17.2. 284
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 Semicolons are placed at the end of the initialization and continuation condition, but not the iteration statement. Just as with while loops, the opening curly bracket is placed on the same line as the for keyword. Code within the loop body is indented, all at the same indentation level. Another observation is that we declared the index variable i prior to the for loop. Some languages allow you to declare the index variable in the initialization statement, for example for(int i=1; i<=10; i++) . Doing so scopes the index variable to the loop and so i would be out-of-scope before and after the loop body. This is a nice convenience and is generally good practice. However, C89 and prior standards do not allow you to do this; the variable must be declared prior to the loop structure. C99 and newer standards do allow you to do this and some compilers will be somewhat forgiving when you use the newer syntax (by supporting their own non-standard extensions to C). For maximum portability, we’ll follow the older convention. 17.3. Do-While Loops C supports do-while loops. Recall that the difference between a while loop and a do-while loop is when the continuation condition is checked. For a while loop it is prior to the beginning of the loop body and in a do-while loop it is at the end of the loop. This means that a do-while always executes at least once. An example can be found in Code Sample 17.4. Note the syntax and style: the opening curly bracket is again on the same line as the keyword do . The while keyword and continuation condition are on the same line as the closing curly bracket. In a slight departure from prior syntax, a semicolon does 285
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, you iterate an index variable, typically with a for loop. However, there are some syntactic tricks that you can use to get the same effect. Some of this will be a preview of Chapter 20 where we discuss arrays in C, but in short, you can assign a variable to an element in an array in iteration statement: 1 double arr[] = {1.41, 2.71, 3.14}; 2 int n = 3; 3 int i = 0; 4 double x; 5 for(x=arr[0]; i<n; x=arr[++i]) { 6 //x now holds the i-th element in arr 7 } The initialization sets the variable x to the first element in the array, arr[0] . The loop continues for as many elements as there are in the array, n . The iteration does two things: it assigns x to the next element in the array while at the same time incrementing the index variable using the prefix increment operator (see Section 2.3.6). 286
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-negative value of x . 1 double x = 32145.234; 2 int k = 0; 3 while(x > 10) { 4 x = x / 10; //or: x /= 10; 5 k++; 6 } Code Sample 17.5.: Normalizing a Number with a While Loop in C 17.5.2. Summation Let’s revisit the example from Section 4.2.1 in which we computed the sum of integers 1 + 2 + · · · + 10. The code is presented in Code Sample 17.6 1 int i; 2 int sum = 0; 3 for(i=1; i<=10; i++) { 4 sum += i; 5 } Code Sample 17.6.: Summation of Numbers using a For Loop in C Of course we could easily have generalized the code somewhat. Instead of computing a sum up to a particular number, we could have written it to sum up to another variable n , in which case the for loop would instead look like the following. 287
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++) { 5 for(j=0; j<m; j++) { 6 printf("(i, j) = (%d, %d)\n", i, j); 7 } 8 } Code Sample 17.7.: Nested For Loops in C The inner loop executes for j = 0, 1, 2, . . . , 19 < m = 20 for a total of 20 itera- tions. However, it executes 20 times for each iteration of the outer loop. Since the outer loop executes for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the printf() statement execute is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed. 17.5.4. Paying the Piper Let’s adapt the solution for the loan amortization schedule we developed in Section 4.7.3. First, we’ll read the principle, terms, and interest as command line inputs. Adapting the formula for the monthly payment and using the standard math library’s pow() function, we get 288
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 currency are rounded to the nearest cent. The standard math library does have a round() function, but it only rounds to the nearest whole number, not the nearest 100th. However, we can adapt the “off-the-shelf” solution to fit our needs. If we take the number, multiply it by 100, we get (say) 4387.1 which we can now round to the nearest whole number, giving us 4387. We can then divide by 100 to get a number that has been rounded to the nearest 100th! In C, we could simply do the following. monthlyPayment = round(monthlyPayment * 100.0) / 100.0; We can use the same trick to round the monthly interest payment and any other number expected to be whole cents. To output our numbers, we use printf() and take care to align our columns to make it look nice. To finish our adaptation, we handle the final month separately to account for an over/under payment due to rounding. The full solution can be found in Code Sample 17.8. 289
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 = principle; 17 double monthlyInterestRate = apr / 12.0; 18 int i; 19 20 //monthly payment 21 double monthlyPayment = (monthlyInterestRate * principle) / 22 (1 - pow( (1 + monthlyInterestRate), -n)); 23 //round to the nearest cent 24 monthlyPayment = round(monthlyPayment * 100.0) / 100.0; 25 26 printf("Principle: $%.2f\n", principle); 27 printf("APR: %.4f%%\n", apr*100.0); 28 printf("Months: %d\n", n); 29 printf("Monthly Payment: $%.2f\n", monthlyPayment); 30 31 //for the first n-1 payments in a loop: 32 for(i=1; i<n; i++) { 33 // compute the monthly interest, rounded: 34 double monthlyInterest = 35 round( (balance * monthlyInterestRate) * 100.0) / 100.0; 36 // compute the monthly principle payment 37 double monthlyPrinciplePayment = monthlyPayment - monthlyInterest; 38 // update the balance 39 balance = balance - monthlyPrinciplePayment; 40 // print i, monthly interest, monthly principle, new balance 41 printf("%d\t$%10.2f $%10.2f $%10.2f\n", i, monthlyInterest, 42 monthlyPrinciplePayment, balance); 43 } 44 45 //handle the last month and last payment separately 46 double lastInterest = round( (balance * monthlyInterestRate) * 100.0) / 100.0; 47 double lastPayment = balance + lastInterest; 48 49 printf("Last payment = $%.2f\n", lastPayment); 50 51 return 0; 52 } Code Sample 17.8.: Loan Amortization Program in C 290
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, careful thought must be made as to the naming of your functions. This is because C does not support function overloading. When you name a function, that is the only function that can have that name. Consequently, you cannot, in general, use the same function names as defined in the standard libraries or any other 3rd party library that you would like to use in your programs. C supports both call by value and call by reference using pointers (see Section 18.2). C also supports vararg functions ( printf() being a prime example) and allows you to define vararg functions, but we will not cover them in depth here. Finally, parameters are not, in general, optional. For modern versions of C the omission of parameters is a syntax error. For older versions, complex rules dictate what happens when arguments are omitted, but doing so usually results in garbage. 18.1. Defining & Using Functions For modern C, defining functions is a two step process. First, you declare a function and its signature using a prototype. Then you define the function by providing a function body that defines what the function does. 18.1.1. Declaration: Prototypes Just as with variables, functions in C must be declared before they can be used. The modern way to declare a function in C is to use a prototype declaration which specifies the function’s signature including its return type, identifier, and parameters. However, a prototype does not include the actual body of function. Instead, the function’s definition, which includes the function body is included later in the program. Consequently, a prototype always ends with a semicolon. 291
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 originally developed for Java but has since been adopted by many other languages. 1 /** 2 * Computes the sum of the two arguments. 3 */ 4 int sum(int a, int b); 5 6 /** 7 * Computes the Euclidean distance between the 2-D points, 8 * (x1,y1) and (x2,y2). 9 */ 10 double getDistance(double x1, double y1, double x2, double y2); 11 12 /** 13 * Computes a monthly payment for a loan with the given 14 * principle at the given APR (annual percentage rate) which 15 * is to be repaid over the given number of terms (usually 16 * months). 17 */ 18 double getMonthlyPayment(double principle, double apr, int terms); In each of these, the return type is the first thing specified. The function identifier (name) is then specified. Function names must follow the same naming rules as variables: they must begin with an alphabetic character and may contain alphanumeric characters as well as underscores. Using modern coding conventions we usually name functions using lower camel casing. Each prototype ends with a semicolon. Further, prototypes do not specify what the function does, they only specify its signature. Later in the program, we can provide the actual definition of each function by using the following syntax. We repeat the signature, but instead of using a semicolon, we provide a code block, enclosed using opening/closing curly brackets, that specifies the function body. Here are the definitions from the prototype examples above: 1 int sum(int a, int b) { 2 return (a + b); 3 } 292
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 payment = (principle * rate) / (1-pow(1+rate, -terms)); 14 return payment; 15 } The keyword return is used to specify the value that is returned to the calling function. 18.1.2. Void Functions The keyword void can be used in C to indicate a function does not return a value, in which case it is called a “void function.” Though it is not necessary, it is still good practice to include a return statement. 1 //prototype: 2 void printCopyright(); 3 4 //definition: 5 void printCopyright() { 6 printf("(c) Bourke 2015\n"); 7 return; 8 } In the example above, we’ve also illustrated how to define a function that has no inputs. Some sources may include an explicit void keyword as a parameter to indicate the function takes no parameters as in void printCopyright(void); . 293
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 file extension, .c . We’ve seen this before with the standard libraries: we use #include <math.h> to “include” the math library’s header file in our code. This essentially brings in the math library function prototypes so that we can write calls to functions like sqrt() or sin() . Only when we compile do we actually need to link our code to the function definitions. When we separate prototypes into header files and definitions into source files we also need to “include” the prototypes in our source file just as we would need to include them in any other file in which we use one of the functions. Suppose our functions above have their prototypes in a file named utils.h and their definitions in a file named utils.c . In the utils.c source file we would typically use the following syntax to include the header file: #include "utils.h" We use the double quote syntax with user-defined libraries while the usual less-than/greater- than syntax is used with standard libraries. With the less-than/greater-than syntax, the compiler will attempt to look for the header file(s) in a specified system directory which it will fail to find if it is a user-defined library. Furthermore, other elements are usually included in header files such as preprocessor directives and other declarations (such as enumerated types and structures which we introduce later). 18.1.4. Calling Functions Once a function has been defined, or at least a prototype has been brought into scope via an #include statement, you can write code to call your function(s). The syntax for doing so is to simply provide the function name followed by parentheses containing values or variables to pass to the function. Some examples: 1 int a = 10, b = 20; 2 int c = sum(a, b); //c contains the value 30 3 4 //invoke a function with literal values: 5 double dist = getDistance(0.0, 0.0, 10.0, 20.0); 6 7 //invoke a function with a combination: 8 double p = 1500.0; 294
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 creates an integer variable and sets it equal to 10. In more detail, this line creates a spot in memory (typically 32 bits) and stores a binary representation of the value 10 at that location. In many instances, we don’t care where the variable is stored in memory. However, we may have need to communicate that memory location to other functions. To do so, we can use pointers. A pointer in C is a reference to a memory location. Because different types ( int , double , char ) take a different amount of memory, it is necessary to have a pointer for each type. That is, a pointer that points to a memory location that stores an int or a pointer that points to a memory location that stores a double , etc. The syntax for declaring a pointer is to use an asterisk. 1 //regular variable declarations 2 int a; 3 double b; 4 5 //pointer variable declarations 6 int *ptrA; 7 double *ptrB; If ptrA represents a memory location, what values can it take on? A memory location is just a number, so you could do something like the following. ptrA = 10; 295
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 it may not even exist as a valid memory address. Attempts to access the value stored at an arbitrary memory location may be illegal and may result in the operating system killing the program with a segmentation fault or similar error. There are many reasons why a program should not be allowed access to arbitrary memory locations, but one of the prime reasons is security. Imagine if the operating system allowed a program access to any part of memory; in particular memory that contained sensitive information such as passwords or secret Secure Sockets Layer (SSL) keys. To prevent this, operating systems generally only allow a program to access its own memory. Referencing Operator So how do we assign a valid value to a pointer? We do so using a referencing operator. Given a normal variable as above, we place an ampersand in front of it to get the memory address of the variable. For example: 1 ptrA = &a; 2 ptrB = &b; The operation &a results in the memory address of the variable a and we can assign it to a pointer value. The pointer type and variable type should match; an integer pointer should point to an int , a double pointer should point to a double . Making a double pointer point to an int variable type such as ptrB = &a; is valid syntax, but since the two types use different amounts of memory you may get garbage results. There is a special value used in C called NULL which is a (case-sensitive) keyword used for an uninitialized, undefined, empty or otherwise invalid or meaningless value. In the context of memory locations, NULL “points” to nothing. As with regular variables, its best practice to initialize pointer values to NULL . For example, int *ptrA = NULL; Without an initialization, the pointer may point to a random memory address which may be dangerous to attempt to access. You can also test whether or not a pointer points to 296
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 inverse operation, the dereferencing operator which again uses an asterisk. Given a pointer variable ptrA , we apply an asterisk in front of it to turn it into a regular variable. Consider the following example. 1 //declare a normal integer variable 2 int a = 10; 3 //declare a pointer and initialize it to NULL 4 int *ptrA = NULL; 5 6 //point ptrA to a's memory location 7 ptrA = &a; 8 9 //change the value of the variable a using its pointer 10 *ptrA = 20; 11 12 //now the variable a has a value of 20: 13 printf("a = %d\n", a); //prints "a = 20" Figure 18.1 depicts how these lines of code operate in memory. 18.2.1. Passing By Reference Now that we have the ability to reference a memory location using pointers, we can write functions that pass variables by reference. To do so, we use the same asterisk syntax 297
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 ptrA 0xc260ec84 0xc260ec88 ... Address Contents ptrA = &a; (b) Making ptrA point to the variable a ’s memory location. The value stored in the vari- able ptrA is a memory address. 0xc260ec80 0xc260ec84 20 a 0xc260ec88 0xf289fb14 0xf289fb18 ptrA 0xc260ec84 0xc260ec88 ... Address Contents *ptrA = 20; (c) Dereferencing ptrA and assigning a value changes the value stored at what it points to. Figure 18.1.: Pointer Operations. Pointers can be made to point to other variable’s memory locations. You can manipulate/access values of variables via their pointers using dereferencing. 298
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 variables passed by reference. 12 */ 13 void swap(int *a, int *b); In the function definitions, we can use the dereferencing operator to access or modify the value stored in the variable pointed to by the pointer. 1 void sum(int a, int b, int *c) { 2 int x = a + b; 3 *c = x; 4 return; 5 } 6 7 void swap(int *a, int *b) { 8 int temp = *a; 9 *a = *b; 10 *b = temp; 11 return; 12 } To invoke these functions, we need to pass pointers to the functions appropriately. We could do this by creating pointer variables or using the referencing operator directly. 1 int x = 10; 2 int y = 20; 3 int c; 299
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. We needed to place an ampersand in front of each variable in order to pass the variable by reference so that scanf() could place the results into the respective memory locations. If the variables had been passed by value, then scanf() would not have been able to manipulate their values. You can also specify functions to return pointers which we discuss in detail in Chapter 20. 18.2.2. Function Pointers Functions are just pieces of code that reside somewhere in memory just as variables do. Since we can create pointers that point to variables, it makes sense to be able to create variables that point to functions too! These are referred to as function pointers. The syntax for declaring function pointers is similar to variable pointers. However, since a function’s signature involves a return type and parameter list, these need to be specified. For example, suppose we wanted to create a function pointer that could point to the math library’s sqrt() function which takes a single double parameter and returns a double value. double (*ptrToSqrt)(double) = NULL; The above line creates a function pointer that can point to any function that takes a single double parameter and returns a double value. As is good practice, we’ve initialized it to point to NULL . The function pointer itself is named ptrToSqrt . To make it point to the sqrt() function we can use the following syntax. ptrToSqrt = sqrt; This is because a function’s identifier acts as a pointer as well! Once we have a pointer to a function, we can invoke the function via its pointer as we would any other function call. 300
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 = sqrt; 10 x = ptr(2.0); //x contains 1.4142... 11 //or we can make it point to fabs 12 ptr = fabs; 13 x = ptr(-10.5); //x contains 10.5 You generally want to create and use function pointers when passing and returning functions as arguments to other functions as callbacks. We discuss this in further detail in Chapter 25. 18.3. Examples 18.3.1. Generalized Rounding Recall that the standard math library provides a round() function that rounds a number to the nearest whole number. We’ve had need to round to cents as well. We now have the ability to write a function to do this for us. Before we do, however, let’s think more generally. What if we wanted to round to the nearest tenth? Or what if we wanted to round to the nearest 10s or 100s place? Let’s write a general purpose rounding function that allows us to specify which decimal place to round to. The most natural input values would be to specify the place using an integer exponent. That is, if we wanted to round to the nearest tenth, then we would pass it −1 as 0.1 = 10−1, −2 if we wanted to round to the nearest 100th, etc. In the other direction, passing in 0 would correspond to the usual round function, 1 to the nearest 10s spot, and so on. Moreover, we could demonstrate good code reuse (as well as procedural abstraction) by scaling the input value and reusing the functionality already provided 301
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 two files are presented here: 1 /** 2 * Rounds to the nearest digit specified by the place 3 * argument. In particular to the (10^place)-th digit 4 */ 5 double roundToPlace(double x, int place); 6 7 /** 8 * Rounds to the nearest cent 9 */ 10 double roundToCents(double x); 1 #include <math.h> 2 #include "round.h" 3 4 double roundToPlace(double x, int place) { 5 double scale = pow(10, -place); 6 double rounded = round(x * scale) / scale; 7 return rounded; 8 } 9 10 double roundToCents(double x) { 11 return roundToPlace(x, -2); 12 } Observe that neither of these files contains a main() function. By themselves they would not be able to be compiled into an executable program. We’ve essentially built a small library of rounding functions. We could compile them though into a binary object file using gcc (something like gcc -c round.c ). We could then link into the object file when compiling an executable program that uses these functions. 302
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 them, thereby communicating (though not strictly returning) multiple values. Consider again the problem of computing the roots of a quadratic equation, ax2 + bx + c = 0 using the quadratic formula, −b ± √ b2 −4ac 2a Since there are two roots, we may have to write two functions, one for the “plus” root and one for the “minus” root both of which take the coefficients, a, b, c as arguments. However, if we wrote a single function that took the coefficients as parameters by value as well as two other parameters by reference, we could compute both root values and place each one in two pass by reference variables. 1 void quadraticRoots(double a, double b, double c, 2 double *root1, double *root2) { 3 double discriminant = sqrt(b*b - 4*a*c); 4 *root1 = (-b + discriminant) / (2*a); 5 *root2 = (-b - discriminant) / (2*a); 6 return; 7 } By using pass by reference variables, we avoid multiple functions. We also note that the return value in this case is unused since we are “returning” the root values in the two pass by reference variables. This frees up the return value to be used to communicate errors to the calling function. Recall that there could be several “bad” inputs to this function. The roots could be complex values, the coefficient a could be zero, etc. And now that we are dealing with pointers, the pointers could be invalid (point to NULL ). In the next chapter, we examine how we can use the return value to communicate different errors to the calling function, letting it handle those errors. 303
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. One way that we’ve already seen to handle errors in C is to use the exit() function in the standard library. This function immediately terminates the execution of our program and “returns” an integer valued “exit code.” This exit code can be used to communicate errors between different processes. The process that executed the program can use it to determine if the program exited with or without an error. By convention, 0 indicates an error while a non-zero value indicates an error. Using the exit() function should only be done when an error should be considered fatal or severe enough that the program should immediately terminate. 19.1. Language Supported Error Codes In the standard libraries, some functions are designed to indicate an error by returning a special “flag” value such as −1 or NULL . In general, though, the standard library functions communicate an error code represented as an integer value. As previously mentioned, C uses the convention that 0 indicates “no error” while a non-zero value indicates an error. Error codes are communicated through a special global variable called errno which is defined in the errno.h standard header file. This header file also defines several macros that are identified with various error codes. The C standard actually only requires the following three error codes to be supported. • EDOM indicates an error in the domain of a function; that is, an error with respect to the function’s input value(s). For example, calling the math library’s sqrt(-1) on a negative value results in an EDOM error as C does not support complex numbers. • ERANGE indicates an error in the range of a function; that is, an error with respect to the function’s output value(s). For example, calling the math library’s log(0) 305
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 and supported (see POSIX Error Codes below). When an error occurs, a function will set the global variable errno to one of these error code values. Upon returning from a function, you can check for these error codes. Since these error codes are represented as integers, you simply use the numerical comparison operator, == . You can check for no error by making a comparison to zero. In addition, the standard string library, defined in the header file, string.h provides a function, char * strerror(errno) that can be used to map the value in errno to a human-readable error message. We discuss strings in detail later on, but we can see how to use this function in Code Sample 19.1. The output of this program is as follows. result: 1.4142, error: 0 result: -nan, error: 33 it was an EDOM error Error Message: Numerical argument out of domain result: -inf, error: 34 it was an ERANGE error Error Message: Numerical result out of range For this particular system, the EDOM and ERANGE error codes were associated with the integer values 33 and 34 respectively. These numbers are not necessarily the same on all systems so comparisons must be made against the macro names for portability. 19.1.1. POSIX Error Codes POSIX is an IEEE set of standards for maintaining compatibility between various operating systems. It defines several rules and expectations that operating systems must adhere to in order to be POSIX compliant. Such standards allow developers to develop code that should be interoperable among a collection of different operating systems, reducing the need for rewrites and reimplementations for different systems. In particular, POSIX compliant systems define many other error codes (see [3]) that 306
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 and EDOM error... 17 x = sqrt(a); 18 printf("result: %.4f, error: %d\n", x, errno); 19 20 //make a comparison 21 if(errno == EDOM) { 22 printf("it was an EDOM error\n"); 23 } 24 25 //error messages can be accessed via: 26 char *errMsg = strerror(errno); 27 printf("Error Message: %s\n", errMsg); 28 29 //ERANGE error 30 x = log(c); 31 printf("result: %.4f, error: %d\n", x, errno); 32 33 if (errno == ERANGE) { 34 printf("it was an ERANGE error\n"); 35 } 36 37 //error messages can be accessed via: 38 errMsg = strerror(errno); 39 printf("Error Message: %s\n", errMsg); 40 41 return 0; 42 43 } Code Sample 19.1.: Using the errno.h library 307
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 variable, however, we may run into compatibility issues with the standard error codes or POSIX error codes. Instead, it may be more appropriate to do error handling by utilizing the return value of a function to communicate an error code. We could design our functions to always return an int value to indicate an error: 0 for no error and some non-zero value to indicate various different types of errors. Of course, as a consequence any value that needs to be “returned” to the calling function would need to be done so via a pass by reference variable. As an example, let’s revisit the quadratic roots example in Section 18.3.2. By returning the two output values via pass by reference variables, we freed up the return value. We can now modify our function to return an integer indicating an error code instead. Previously we had identified several different types of errors: division by zero (if a = 0), complex roots (if b2 −4ac < 0) and a NULL pointer error if the variables passed by reference were NULL . We can now modify our function to check for these errors and return an appropriate error code. We return zero in the event that no error was encountered. 1 int quadraticRoots(double a, double b, double c, 2 double *root1, double *root2) { 3 if(a == 0) { 4 return 1; 5 } else if( b*b - 4*a*c < 0 ) { 6 return 2; 7 } else if(root1 == NULL || root2 == NULL) { 8 return 3; 9 } 10 double discriminant = sqrt(b*b - 4*a*c); 11 *root1 = (-b + discriminant) / (2*a); 12 *root2 = (-b - discriminant) / (2*a); 13 return 0; 14 } Now when a function invokes our quadraticRoots() it can check to see what kind of 308
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 various integers. The numbers themselves are meaningless and someone using them would need to constantly refer to documentation to understand which integer corresponded to which error condition. It would be much better if we could follow the strategy of the errno and define human- readable identifiers for each error code. We could accomplish this by defining macros, but another solution is to use an enumerated type. 19.3. Enumerated Types C allows you to define enumerated types which allow you to define a fixed list of possible values. For example, the days of the week or months of the year are possible values used in a date. However, they are more-or-less fixed (no one will be adding a new day of the week or month any time soon). An enumerated type allows us to define these values using human-readable keywords (much like the #define macro). To declare an enumerated type we use the keywords typedef enum (short for type definition and enumeration). We then provide a comma delimited list of keywords inside a code block. At the end of the code block we provide the type’s identifier. That is, the name of the type itself. For example, the names of integer and floating-point types in C are int and double respectively. This identifier gives our type a name that we can later use to declare variables of that type. Consider the following example. 1 typedef enum { 2 SUNDAY, 3 MONDAY, 4 TUESDAY, 5 WEDNESDAY, 6 THURSDAY, 7 FRIDAY, 8 SATURDAY 9 } DayOfWeek; In this example we’ve defined an enumeration of the days of the week. The name of the type itself is DayOfWeek and we can now declare variables of this type. The possible 309
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 while the enumerated values follow an uppercase underscore convention. Though our example does not contain a value with multiple words, if it had, we would have used an underscore to separate them. Furthermore, enumerated type declarations are usually placed in separate header files along with function prototype declarations. Care must be taken when using enumerated types, however. Internally, C simply associates integers with the values. Thus, in our example, SUNDAY is actually 0 , MONDAY is 1 , and SATURDAY is 6 . When we do assignments or equality comparisons, we’re actually just comparing integers. Consequently, a DayOfWeek variable may be assigned values that do not correspond to our enumeration. For example, DayOfWeek today = 1000; is valid code and will not (in general) result in any compiler errors or warnings, even though it is assigning an invalid value to the variable. You should only assign valid values to an enumerated type variable. Proper error checking should also be done. Despite this limitation, using enumerated types in C provides an obvious advantage. Without an enumerated type we’d be forced to use a collection of magic numbers to indicate values. Even for something as simple as the days of the week we’d be constantly trying to remember: which day is Wednesday again? I forget, does our week start with Monday or Sunday? Etc. By using an enumerated type these questions are mostly moot as we can use the more human-readable keywords and eliminate the guess work. 19.4. Using Enumerated Types for Error Codes Let’s apply enumerated types to our quadraticRoots() function example from before. First, we define our enumerated type which includes all types of errors including a NO_ERROR type. Note that we start with NO_ERROR as its value will be zero following our convention. 310
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 double *root1, double *root2) { 3 if(a == 0) { 4 return DIV_BY_ZERO_ERROR; 5 } else if( b*b - 4*a*c < 0 ) { 6 return COMPLEX_ROOT_ERROR; 7 } else if(root1 == NULL || root2 == NULL) { 8 return NULL_POINTER_ERROR; 9 } 10 double discriminant = sqrt(b*b - 4*a*c); 11 *root1 = (-b + discriminant) / (2*a); 12 *root2 = (-b - discriminant) / (2*a); 13 return NO_ERROR; 14 } 311
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 use syntax similar to declaring a regular variable, but you use square brackets to designate the variable as an array. Within the square brackets you indicate the size (number of elements) in the array. For example, 1 int arr[5]; 2 double values[10]; The two declarations above create arrays of size 5 and 10 respectively. The array types are also defined using the usual keywords. In this case, arr can only hold int values and values can only hold double values. Arrays follow the same naming rules and conventions as regular variables. Many times, identifiers are made plural as an array naturally holds more than one value. Another way to declare an array is to use the compound declaration and assignment syntax whereby you can initialize an array to hold a certain list of values. 1 int a[] = { 2, 3, 5, 7, 11 }; Using this syntax we do not need to specify the size of the array as the compiler is smart enough to count the number of elements we’ve provided. The elements themselves are denoted inside curly brackets and delimited with commas. 313
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, care must be taken as static arrays are allocated on the stack. The stack is generally small and allocating even a moderately large array on the stack may lead to a stack overflow. In addition, VLAs are not supported in any C++ standard and should be avoided if portable code is desired. Indexing Once an array has been created, its elements can be accessed using indexing. C uses the standard 0-indexing scheme so the first element is at index 0, the second at index 1, etc. Indexing an element involves using the square bracket notation and providing an index. Once indexed, an array element can be treated as a normal variable and can be used with other operators such as the assignment operator or comparison operators. 1 arr[0] = 42; 2 if(arr[4] < 0) { 3 printf("negative!\n"); 4 } 5 printf("arr[1] = %d\n", arr[1]); 314
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 array. For example, arr[-1] or arr[5] would attempt to access an element immediately before the first element and immediately after the last element. Obviously, these elements are not part of the array. If these out-of-bound elements represent a memory space that does not belong to our program, then it is likely that a segmentation fault will occur and terminate our program. However, it is also likely that the memory space surrounding our array does belongs to our program. Still, accessing those blocks of memory may not give us meaningful values and modifying them could corrupt other variable values or generally lead to undefined behavior. It is our responsibility as programmers to write code that does not go beyond the bounds of an array. How can we keep track of the size of the array so that we do not access elements after the last element? With C the responsibility again falls to us. We must always have secondary variables that store the size of an array. If we pass an array to a function (see below), we must also pass a “size” parameter so that the function knows how big the array is. Iteration C provides no foreach loop to iterate over an array. Instead, the most natural way to iterate over the elements is a normal for loop that increments an index variable. 1 int i, n = 10; 2 int arr[n]; 3 for(i=0; i<n; i++) { 4 arr[i] = 5 * i; 5 } The for loop above initializes the variable i to zero, corresponding to the first element in the array. The continuation condition is specifies that the loop continues while i is strictly less than the size of the array. This iteration for loop is idiomatic when dealing with arrays. An alternative was presented in Section 17.4. 315
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 dynamically allocated arrays. The primary function to allocate memory is the memory allocation function, malloc() : void * malloc(size_t size); which takes a single parameter, the number of bytes that you wish to allocate. The type, size_t is an alias for an unsigned integer type, so you can think of it as an integer. Thus, malloc(200) would allocate 200 bytes and return a pointer to the memory space. In some instances, the allocation may fail. For example, if the program or system has run out of available memory or you simply request too much. In the event of a failure, malloc() returns a NULL pointer. The returned value can thus be checked to see if the allocation was successful or not. We don’t have to manually calculate how many bytes we need for an array of a particular size. The macro sizeof() can be used to determine the number of bytes any type of variable requires on a system. For example, sizeof(int) gives the number of bytes an int takes while sizeof(double) gives the number of bytes for a double , etc. Thus, if we want to allocate an array of 100 integers, we could call malloc() as malloc(100 * sizeof(int)); Using sizeof() is actually preferable as some systems may use a different number of bytes for various types. Finally, note the return type of malloc() : it is a void pointer. The malloc() function simply allocates chunks of memory. It doesn’t care that you intend to use the memory to store integers or floating-point numbers. Thus, malloc() returns a “generic” pointer, simply an address in memory. Once we have that pointer we can treat it as an integer pointer, int * or a floating-point pointer, double * depending on what we want to store. One way of doing this is to explicitly cast the void pointer as the pointer that we want. Some examples: 1 int *arr = NULL; 2 double *values = NULL; 3 4 arr = (int *) malloc(sizeof(int) * 10); 316
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 created, a dynamic array can be used just like a static array. You use the array’s identifier as well as an index to access or modify each element. The same rules and pitfalls apply, so care must be taken to not access elements outside the bounds of the array. Finally, when using malloc() it is important to understand that the memory that is allocated is uninitialized. Just as with variables you cannot make any assumptions as to the contents of the memory space that is allocated. It may contain garbage values, it may contain the contents that occupied the memory last time it was used, etc. A full example: 1 int n = 100; 2 int *arr = NULL; 3 arr = (int *) malloc(sizeof(int) * n); 4 if(arr == NULL) { 5 fprintf(stderr, "unable to allocate memory!\n"); 6 exit(1); 7 } 8 for(i=0; i<n; i++) { 9 arr[i] = (i+1) * 10; 10 printf("a[%d] = %d\n", i, arr[i]); 11 } There are other functions that can be used to allocate memory in C. For example, calloc() is similar to malloc() but initializes the contents to zero (null bytes). realloc() can be used to resize an existing memory space (though it may fail if it cannot be expanded). 1Performing an explicit pointer cast is actually not necessary in C as the type system will do an implicit cast for us. Whether explicit or implicit types casts are “better” can evoke debates akin to nerd holy wars. Though there are advantages and disadvantages to both [15], we perform explicit pointer casts in this book as clarity and intent is more important than brevity. Even more important is that explicit pointer casts are necessary in C++ so doing so in our C code makes our code more portable. 317
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 free(arr); Once freed, accessing old memory pointed to by the arr pointer is undefined behavior and may lead to unexpected or fatal results. 20.3. Using Arrays with Functions Since arrays are represented using pointers, we can pass and return arrays to and from functions simply by passing in a pointer. When passing an array to a function, we also need to make sure that we communicate to the function the size of the array as there is no reliable way for the function to determine this. By passing both a pointer and an integer representing the size, we are implicitly indicating that we are passing an array and not just a single value. As an example, the following function takes an array of integers and computes their sum. 1 /** 2 * This function computes the sum of elements in the 3 * given array which contains n elements 4 */ 5 int computeSum(int *arr, int n) { 6 int i; 7 int sum = 0; 8 for(i=0; i<size; i++) { 9 sum += arr[i]; 10 } 11 return sum; 12 } 318
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 array elements. For example, int computeSum(const int *arr, int n) This is enforced by the compiler: if we do attempt to make changes to a const array, it will be a compiler error. We can also create an array in a function and return it as a value. As previously discussed, we will need to do so by creating a dynamically allocated array. For example, the following function creates a deep copy of the given integer array. That is, a completely new array that is a distinct copy of the old array. In contrast, a shallow copy would be if we simply made one reference point to another reference. 1 /** 2 * This function creates a new copy of the given integer 3 * array which contains n elements and returns a pointer 4 * to the new copy. 5 */ 6 int * makeCopy(const int *a, int n) { 7 int *copy = (int *)malloc(sizeof(int) * n); 8 int i; 9 for(i=0; i<n; i++) { 10 copy[i] = a[i]; 11 } 12 return copy; 13 } The function returns an integer pointer. Here we have a similar problem with respect to the size of the array. We only have one return value, which must be the pointer. In this particular example the calling function knows how big the array is because it specified the size by passing in n . In general we could have communicated the size of the returned array through another pass by reference integer variable. 20.4. Multidimensional Arrays C supports multidimensional arrays both static and dynamically allocated; though we’ll only focus on dynamically allocated 2-dimensional arrays. Conceptually, a 2-dimensional 319
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, let’s look at the details of allocation. Consider the following code. 1 int i; 2 int **myMatrix = NULL; 3 myMatrix = (int **)malloc(n * sizeof(int*)); 4 for(i=0; i<n; i++) { 5 myMatrix[i] = (int *)malloc(n * sizeof(int)); 6 } Line 3 invokes malloc() to create an array of n integer pointers, that is int * types. We then go into a loop to iterate over each of these pointers and invoke malloc() again to setup each array. This process is visualized in Figure 20.1. Note the syntax: when we invoke malloc() to create an array of pointers, we use sizeof(int*) to determine how many bytes each integer pointer takes. We also do an explicit type cast of (int **) to match our pointer-to-pointer(s) variable myMatrix . Once the allocation has completed, we can treat myMatrix as a normal 2-dimensional array and index each element with two index variables. 1 int i, j; 2 for(i=0; i<n; i++) { 3 for(j=0; j<n; j++) { 4 myMatrix[i][j] = 0; 5 } 6 } To deallocate and free multidimensional arrays, we need to work backwards. If we imme- diately freed the pointer-to-pointers, free(myMatrix); , we would lose all references to the individual array “rows” and would not be able to free them, resulting in a memory leak. We need to free up each row first, then we can free the pointer-to-pointers. 320
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[0][0] myMatrix[0][1] myMatrix[0][2] · · · myMatrix[0][n-1] *myMatrix[1] ? *myMatrix[2] ? ... *myMatrix[n-1] ? (b) Initialization of the first pointer. On the first iteration of the for loop when i = 0, the first “row” is initialized when malloc() is invoked. **myMatrix *myMatrix[0] myMatrix[0][0] myMatrix[0][1] myMatrix[0][2] · · · myMatrix[0][n-1] *myMatrix[1] myMatrix[1][0] myMatrix[1][1] myMatrix[1][2] · · · myMatrix[1][n-1] *myMatrix[2] ? ... *myMatrix[n-1] ? (c) Initialization of the second pointer. On the second iteration of the for loop when i = 1, the second “row” is initialized. **myMatrix *myMatrix[0] myMatrix[0][0] myMatrix[0][1] myMatrix[0][2] · · · myMatrix[0][n-1] *myMatrix[1] myMatrix[1][0] myMatrix[1][1] myMatrix[1][2] · · · myMatrix[1][n-1] *myMatrix[2] myMatrix[2][0] myMatrix[2][1] myMatrix[2][2] · · · myMatrix[2][n-1] ... *myMatrix[n-1] myMatrix[n-1][0] myMatrix[n-1][1] myMatrix[n-1][2] · · · myMatrix[n-1][n-1] (d) After the termination of the for loop, each row has been initialized and the pointer-to- pointers can be treated like a 2-dimensional array. Figure 20.1.: The process of dynamically allocating a 2-dimensional array of integers using malloc() in a for-loop. 321
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 may not be located in the memory address immediately following the previous row). In general, this is not a problem for most situations (we can expect most implementations of malloc() to be efficient). However, it might be better in some scenarios if the two dimensional array were all one big block of contiguous memory. We can achieve this by a single call to malloc() and some clever pointer manipulation. We do this very similar to the previous example. Our first call to malloc() to set up the pointer-to-pointers is the same. However, instead of calling malloc() over and over in a for loop, we make one single call asking for a number of bytes to accommodate the entire n × m array. We then store the result at the “beginning” of the array (at index zero). In the following example, we will create a 4 × 3 sized matrix. 1 int **m = (int **) malloc(sizeof(int *) * 4); 2 m[0] = (int *) malloc(sizeof(int) * (4 * 3)); We’re not done yet, however. We still need to initialize all of the other pointers. To do so, we dereference the array (once) to get the address of the start of the memory block and then compute an offset from this beginning on where the next “row” should be. Since each row has 3 elements, this arithmetic is simple. 1 for(i=1; i<4; i++) { 2 arr[i] = (*arr + (3 * i)); 3 } 322
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 ] [ 20 21 22 ] [ 30 31 32 ] Which are all stored in one large chunk of memory. To see this, we can print out the memory address of each “row” during a particular run of the program: arr[0] = 0x7fe51b403270 arr[1] = 0x7fe51b40327c arr[2] = 0x7fe51b403288 arr[3] = 0x7fe51b403294 Note that each hexadecimal value differs by 0x0c (that is, 12 bytes): 0x...70 + 0x0c = 0x...7c 0x...7c + 0x0c = 0x...88 0x...88 + 0x0c = 0x...94 This is exactly how many bytes the 3 integers (4 bytes each) take in memory in each “row.” The pointer setup is depicted in Figure 20.2. 323
ComputerScienceOne_Page_357_Chunk1900