├── 9781430264002.jpg ├── LICENSE.txt ├── P101TestSiftUp.c ├── P10xHeapsortSiftDown.c ├── P10xHeapsortSiftDown.exe ├── P10xHeapsortSiftDown.o ├── P10xQuicksort2Partition2.c ├── P10xQuicksort2Partition2.exe ├── P10xQuicksort2Partition2.o ├── P10xQuicksort2Partition2a.c ├── P10xQuicksort2Partition2a.exe ├── P10xQuicksort2Partition2a.o ├── P10xQuicksort3NonRecursive.c ├── P10xQuicksort3NonRecursive.exe ├── P10xQuicksort3NonRecursive.o ├── P10xQuicksortPartition1.c ├── P10xQuicksortPartition1.exe ├── P10xQuicksortPartition1.o ├── P10xShellSort.c ├── P10xShellSort.exe ├── P10xShellSort.o ├── P111DistinctNumbersLinearProbe.c ├── P112DistinctNumbersChaining.c ├── P113WordFrequency.c ├── P11SelectionSort.c ├── P12InsertionSort.c ├── P13StringInsertionSort.c ├── P14BinarySearchString.c ├── P15WordFrequency.c ├── P1xMerge.c ├── P1xParallelSort.c ├── P21SortSearchStruct.c ├── P2xVoting.c ├── P31Test.c ├── P32Test.c ├── P33Test.c ├── P34Function.c ├── P41LLInOrder.c ├── P42LLReverseOrder.c ├── P43LLSortedOrder.c ├── P44Palindrome.c ├── P45MergeSortedLL.c ├── P51ArrayStackReverseNum.c ├── P52LLStackReverseNum.c ├── P53StackHeaderTest.c ├── P54ReverseData.c ├── P55ConvertToBinary.c ├── P56InfixToPostfix.c ├── P56xEvalExpression.c ├── P57ReverseInteger.c ├── P58ReverseIntegerLLQ.c ├── P61Organisms.c ├── P62Maze.c ├── P6xMergeSort.c ├── P71GuessingGame.c ├── P72DrillsInAddition.c ├── P73Nim.c ├── P74BottleCaps.c ├── P75CheckoutSimulation.c ├── P76EstimatingRoot5.c ├── P77EstimatingPi.c ├── P81Average.c ├── P82CompareFiles.c ├── P83ReadTextStoreBinary.c ├── P84ReadBinaryWriteText.c ├── P85BinFileOfStructures.c ├── P86FetchBinaryRecords.c ├── P87CreateIndexedFile.c ├── P88RetrieveIndexedFile.c ├── P89UpdateRandomAccessFile.c ├── P91BuildTraverseBinaryTree.c ├── P92WordFrequency.c ├── README.md ├── btree.in ├── cell.in ├── cell.out ├── contributing.md ├── file1.txt ├── file2.txt ├── heap.in ├── index.bin ├── input.txt ├── maze.in ├── maze.out ├── num.bin ├── numbers.in ├── output.txt ├── p46Countout.c ├── parts.bin ├── parts.txt ├── passage.txt ├── queue0.h ├── queue1.h ├── results.txt ├── shell.in ├── stack.h ├── stack0.h ├── structSort.c ├── votes.txt ├── wordFreq.in └── wordFreq.out /9781430264002.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/9781430264002.jpg -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/LICENSE.txt -------------------------------------------------------------------------------- /P101TestSiftUp.c: -------------------------------------------------------------------------------- 1 | // Program P10.1 2 | 3 | #include 4 | #include 5 | #define MaxHeapSize 100 6 | int main() { 7 | void siftUp(int[], int); 8 | int num[MaxHeapSize + 1]; 9 | int n = 0, number; 10 | FILE * in = fopen("heap.in", "r"); 11 | 12 | while (fscanf(in, "%d", &number) == 1) { 13 | if (n < MaxHeapSize) { //check if array has room 14 | num[++n] = number; 15 | siftUp(num, n); 16 | } 17 | else { 18 | printf("\nArray too small\n"); 19 | exit(1); 20 | } 21 | } 22 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 23 | printf("\n"); 24 | fclose(in); 25 | } //end main 26 | 27 | void siftUp(int heap[], int n) { 28 | //sifts up the value in heap[n] so that heap[1..n] contains a heap 29 | int siftItem = heap[n]; 30 | int child = n; 31 | int parent = child / 2; 32 | while (parent > 0) { 33 | if (siftItem <= heap[parent]) break; 34 | heap[child] = heap[parent]; //move down parent 35 | child = parent; 36 | parent = child / 2; 37 | } 38 | heap[child] = siftItem; 39 | } //end siftUp 40 | -------------------------------------------------------------------------------- /P10xHeapsortSiftDown.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | void heapSort(int[], int); 5 | int num[] = {0, 37, 25, 43, 65, 48, 84, 73, 18, 79, 56, 69, 32}; 6 | int n = 12; 7 | heapSort(num, n); 8 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 9 | printf("\n"); 10 | } //end main 11 | 12 | void siftDown(int key, int num[], int root, int last) { 13 | int bigger = 2 * root; 14 | while (bigger <= last) { //while there is at least one child 15 | if (bigger < last) //there is a right child as well; find the bigger 16 | if (num[bigger+1] > num[bigger]) bigger++; 17 | //'bigger' holds the index of the bigger child 18 | if (key >= num[bigger]) break; 19 | //key is smaller; promote num[bigger] 20 | num[root] = num[bigger]; 21 | root = bigger; 22 | bigger = 2 * root; 23 | } 24 | num[root] = key; 25 | } //end siftDown 26 | 27 | void heapSort(int num[], int n) { 28 | //sort num[1] to num[n] 29 | void siftDown(int, int[], int, int); 30 | //convert the array to a heap 31 | for (int h = n / 2; h >= 1; h--) siftDown(num[h], num, h, n); 32 | 33 | for (int k = n; k > 1; k--) { 34 | int item = num[k]; //extract current last item 35 | num[k] = num[1]; //move top of heap to current last node 36 | siftDown(item, num, 1, k-1); //restore heap properties from 1 to k-1 37 | } 38 | } //end heapSort 39 | 40 | 41 | -------------------------------------------------------------------------------- /P10xHeapsortSiftDown.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xHeapsortSiftDown.exe -------------------------------------------------------------------------------- /P10xHeapsortSiftDown.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xHeapsortSiftDown.o -------------------------------------------------------------------------------- /P10xQuicksort2Partition2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | void quicksort2(int[], int, int); 5 | int num[] = {0, 53, 12, 98, 63, 18, 32, 80, 46, 72, 21}; 6 | int n = 10; 7 | quicksort2(num, 1, n); 8 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 9 | printf("\n"); 10 | } //end main 11 | 12 | void quicksort2(int A[], int lo, int hi) { 13 | //sorts A[lo] to A[hi] in ascending order 14 | int partition2(int[], int, int); 15 | if (lo < hi) { 16 | int dp = partition2(A, lo, hi); 17 | quicksort2(A, lo, dp); 18 | quicksort2(A, dp+1, hi); 19 | } 20 | } //end quicksort2 21 | 22 | int partition2(int A[], int lo, int hi) { 23 | //return dp such that A[lo..dp] <= A[dp+1..hi] 24 | void swap(int[], int, int); 25 | int pivot = A[lo]; 26 | --lo; ++hi; 27 | while (lo < hi) { 28 | do --hi; while (A[hi] > pivot); 29 | do ++lo; while (A[lo] < pivot); 30 | if (lo < hi) swap(A, lo, hi); 31 | } 32 | return hi; 33 | } //end partition2 34 | 35 | void swap(int list[], int i, int j) { 36 | //swap list[i] and list[j] 37 | int hold = list[i]; 38 | list[i] = list[j]; 39 | list[j] = hold; 40 | } //end swap 41 | -------------------------------------------------------------------------------- /P10xQuicksort2Partition2.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort2Partition2.exe -------------------------------------------------------------------------------- /P10xQuicksort2Partition2.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort2Partition2.o -------------------------------------------------------------------------------- /P10xQuicksort2Partition2a.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | void quicksort2(int[], int, int); 6 | int num[] = {0, 53, 12, 98, 63, 18, 32, 80, 46, 72, 21}; 7 | int n = 10; 8 | quicksort2(num, 1, n); 9 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 10 | printf("\n"); 11 | } //end main 12 | 13 | void quicksort2(int A[], int lo, int hi) { 14 | //sorts A[lo] to A[hi] in ascending order 15 | int partition2a(int[], int, int); 16 | if (lo < hi) { 17 | int dp = partition2a(A, lo, hi); 18 | quicksort2(A, lo, dp); 19 | quicksort2(A, dp+1, hi); 20 | } 21 | } //end quicksort2 22 | 23 | int partition2a(int A[], int lo, int hi) { 24 | //return dp such that A[lo..dp] <= A[dp+1..hi] 25 | void swap(int[], int, int); 26 | int random(int, int); 27 | //choose a random pivot 28 | swap(A, lo, random(lo, hi)); 29 | int pivot = A[lo]; 30 | --lo; ++hi; 31 | while (lo < hi) { 32 | do --hi; while (A[hi] > pivot); 33 | do ++lo; while (A[lo] < pivot); 34 | if (lo < hi) swap(A, lo, hi); 35 | } 36 | return hi; 37 | } //end partition2a 38 | 39 | void swap(int list[], int i, int j) { 40 | //swap list[i] and list[j] 41 | int hold = list[i]; 42 | list[i] = list[j]; 43 | list[j] = hold; 44 | } //end swap 45 | 46 | int random(int m, int n) { 47 | //returns a random integer from m to n, inclusive 48 | int offset = rand()/(RAND_MAX + 1.0) * (n - m + 1); 49 | return m + offset; 50 | } //end random 51 | -------------------------------------------------------------------------------- /P10xQuicksort2Partition2a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort2Partition2a.exe -------------------------------------------------------------------------------- /P10xQuicksort2Partition2a.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort2Partition2a.o -------------------------------------------------------------------------------- /P10xQuicksort3NonRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct { 5 | int left, right; 6 | } StackData; 7 | 8 | #include 9 | 10 | int main() { 11 | void quicksort3(int[], int, int); 12 | int num[] = {0, 53, 12, 98, 63, 18, 32, 80, 46, 72, 21}; 13 | int n = 10; 14 | quicksort3(num, 1, n); 15 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 16 | printf("\n"); 17 | } //end main 18 | 19 | void quicksort3(int A[], int lo, int hi) { 20 | int partition2a(int[], int, int); 21 | StackData newStackData(int, int); 22 | Stack S = initStack(); 23 | push(S, newStackData(lo, hi)); 24 | int stackItems = 1, maxStackItems = 1; 25 | while (!empty(S)) { 26 | --stackItems; 27 | StackData d = pop(S); 28 | if (d.left < d.right) { //if the sublist is > 1 element 29 | int dp = partition2a(A, d.left, d.right); 30 | if (dp - d.left + 1 < d.right - dp) { //compare lengths of sublists 31 | push(S, newStackData(dp+1, d.right)); 32 | push(S, newStackData(d.left, dp)); 33 | } 34 | else { 35 | push(S, newStackData(d.left, dp)); 36 | push(S, newStackData(dp+1, d.right)); 37 | } 38 | stackItems += 2; //two items added to stack 39 | } //end if 40 | if (stackItems > maxStackItems) maxStackItems = stackItems; 41 | } //end while 42 | printf("Max stack items: %d\n\n", maxStackItems); 43 | } //end quicksort3 44 | 45 | int partition2a(int A[], int lo, int hi) { 46 | //return dp such that A[lo..dp] <= A[dp+1..hi] 47 | void swap(int[], int, int); 48 | int random(int, int); 49 | //choose a random pivot 50 | swap(A, lo, random(lo, hi)); 51 | int pivot = A[lo]; 52 | --lo; ++hi; 53 | while (lo < hi) { 54 | do --hi; while (A[hi] > pivot); 55 | do ++lo; while (A[lo] < pivot); 56 | if (lo < hi) swap(A, lo, hi); 57 | } 58 | return hi; 59 | } //end partition2a 60 | 61 | void swap(int list[], int i, int j) { 62 | //swap list[i] and list[j] 63 | int hold = list[i]; 64 | list[i] = list[j]; 65 | list[j] = hold; 66 | } //end swap 67 | 68 | int random(int m, int n) { 69 | //returns a random integer from m to n, inclusive 70 | int offset = rand()/(RAND_MAX + 1.0) * (n - m + 1); 71 | return m + offset; 72 | } //end random 73 | 74 | StackData newStackData(int a, int b) { 75 | StackData temp; 76 | temp.left = a; 77 | temp.right = b; 78 | return temp; 79 | } //end newStackData 80 | 81 | 82 | -------------------------------------------------------------------------------- /P10xQuicksort3NonRecursive.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort3NonRecursive.exe -------------------------------------------------------------------------------- /P10xQuicksort3NonRecursive.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksort3NonRecursive.o -------------------------------------------------------------------------------- /P10xQuicksortPartition1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | void quicksort(int[], int, int); 5 | int num[] = {0, 53, 12, 98, 63, 18, 32, 80, 46, 72, 21}; 6 | int n = 10; 7 | quicksort(num, 1, n); 8 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 9 | printf("\n"); 10 | } //end main 11 | 12 | void quicksort(int A[], int lo, int hi) { 13 | //sorts A[lo] to A[hi] in ascending order 14 | int partition1(int[], int, int); 15 | if (lo < hi) { 16 | int dp = partition1(A, lo, hi); 17 | quicksort(A, lo, dp-1); 18 | quicksort(A, dp+1, hi); 19 | } 20 | } //end quicksort 21 | 22 | int partition1(int A[], int lo, int hi) { 23 | //partition A[lo] to A[hi] using A[lo] as the pivot 24 | void swap(int[], int, int); 25 | int pivot = A[lo]; 26 | int lastSmall = lo; 27 | for (int h = lo + 1; h <= hi; h++) 28 | if (A[h] < pivot) { 29 | ++lastSmall; 30 | swap(A, lastSmall, h); 31 | } 32 | //end for 33 | swap(A, lo, lastSmall); 34 | return lastSmall; //return the division point 35 | } //end partition1 36 | 37 | void swap(int list[], int i, int j) { 38 | //swap list[i] and list[j] 39 | int hold = list[i]; 40 | list[i] = list[j]; 41 | list[j] = hold; 42 | } 43 | -------------------------------------------------------------------------------- /P10xQuicksortPartition1.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksortPartition1.exe -------------------------------------------------------------------------------- /P10xQuicksortPartition1.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xQuicksortPartition1.o -------------------------------------------------------------------------------- /P10xShellSort.c: -------------------------------------------------------------------------------- 1 | // Shell sort 2 | 3 | #include 4 | #include 5 | #define MaxSize 100 6 | int main() { 7 | void hsort(int[], int, int); 8 | int num[MaxSize + 1]; 9 | int n = 0, number; 10 | FILE * in = fopen("shell.in", "r"); 11 | 12 | int incr[] = {3, 8, 3, 1}; //first 3 is the number of increments 13 | 14 | while (fscanf(in, "%d", &number) == 1) { 15 | if (n < MaxSize) num[++n] = number; 16 | else { 17 | printf("\nArray too small\n"); 18 | exit(1); 19 | } 20 | } 21 | //perform Shell sort with increments 8, 3 and 1 22 | // hsort(num, n, 8); 23 | // hsort(num, n, 3); 24 | // hsort(num, n, 1); 25 | 26 | for (int i = 1; i <= incr[0]; i++) hsort(num, n, incr[i]); 27 | 28 | for (int h = 1; h <= n; h++) printf("%d ", num[h]); 29 | printf("\n"); 30 | fclose(in); 31 | } //end main 32 | 33 | void hsort(int A[], int n, int h) { 34 | for (int k = h + 1; k <= n; k++) { 35 | int j = k - h; //j will index elements k - h, k - 2h, k - 3h, etc 36 | int key = A[k]; 37 | while (j > 0 && key < A[j]) { 38 | A[j + h] = A[j]; 39 | j = j - h; 40 | } 41 | A[j + h] = key; 42 | } 43 | } //end hsort 44 | -------------------------------------------------------------------------------- /P10xShellSort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xShellSort.exe -------------------------------------------------------------------------------- /P10xShellSort.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/P10xShellSort.o -------------------------------------------------------------------------------- /P111DistinctNumbersLinearProbe.c: -------------------------------------------------------------------------------- 1 | // Program P11.1 2 | 3 | #include 4 | #include 5 | #define MaxNumbers 20 6 | #define N 23 7 | #define Empty 0 8 | 9 | int main() { 10 | FILE * in = fopen("numbers.in", "r"); 11 | int h, key, num[N + 1]; 12 | for (h = 1; h <= N; h++) num[h] = Empty; 13 | int distinct = 0; 14 | while (fscanf(in, "%d", &key) == 1) { 15 | int loc = key % N + 1; 16 | while (num[loc] != Empty && num[loc] != key) loc = loc % N + 1; 17 | if (num[loc] == Empty) { //key is not in the table 18 | if (distinct == MaxNumbers) { 19 | printf("\nTable full: %d not added\n", key); 20 | exit(1); 21 | } 22 | num[loc] = key; 23 | distinct++; 24 | } 25 | } 26 | printf("\nThere are %d distinct numbers\n", distinct); 27 | fclose(in); 28 | } //end main 29 | 30 | -------------------------------------------------------------------------------- /P112DistinctNumbersChaining.c: -------------------------------------------------------------------------------- 1 | // Program P11.2 2 | 3 | #include 4 | #include 5 | #define N 13 6 | #define Empty 0 7 | 8 | typedef struct node { 9 | int num; 10 | struct node *next; 11 | } Node, *NodePtr; 12 | 13 | NodePtr newNode(int n) { 14 | NodePtr p = (NodePtr) malloc(sizeof(Node)); 15 | p -> num = n; 16 | p -> next = NULL; 17 | return p; 18 | } 19 | 20 | int main() { 21 | int key, search(int, NodePtr[], int); 22 | void printList(NodePtr); 23 | FILE * in = fopen("numbers.in", "r"); 24 | NodePtr hash[N+1]; 25 | for (int h = 1; h <= N; h++) hash[h] = NULL; 26 | int distinct = 0; 27 | while (fscanf(in, "%d", &key) == 1) 28 | if (!search(key, hash, N)) distinct++; 29 | 30 | printf("\nThere are %d distinct numbers\n\n", distinct); 31 | for (int h = 1; h <= N; h++) 32 | if (hash[h] != NULL) { 33 | printf("hash[%d]: ", h); 34 | printList(hash[h]); 35 | } 36 | fclose(in); 37 | } //end main 38 | 39 | int search(int inKey, NodePtr hash[], int n) { 40 | //return 1 if inKey is found; 0, otherwise 41 | //insert a new key in its appropriate list so list is in order 42 | NodePtr newNode(int); 43 | int k = inKey % n + 1; 44 | NodePtr curr = hash[k]; 45 | NodePtr prev = NULL; 46 | while (curr != NULL && inKey > curr -> num) { 47 | prev = curr; 48 | curr = curr -> next; 49 | } 50 | if (curr != NULL && inKey == curr -> num) return 1; //found 51 | //not found; inKey is a new key; add it so list is in order 52 | NodePtr np = newNode(inKey); 53 | np -> next = curr; 54 | if (prev == NULL) hash[k] = np; 55 | else prev -> next = np; 56 | return 0; 57 | } //end search 58 | 59 | void printList(NodePtr top) { 60 | while (top != NULL) { 61 | printf("%2d ", top -> num); 62 | top = top -> next; 63 | } 64 | printf("\n"); 65 | } //end printList 66 | 67 | -------------------------------------------------------------------------------- /P113WordFrequency.c: -------------------------------------------------------------------------------- 1 | // Program P11.3 2 | 3 | #include 4 | #include 5 | #include 6 | #define MaxWordSize 20 7 | #define MaxWords 10 8 | #define N 13 9 | #define Empty "" 10 | typedef struct { 11 | char word[MaxWordSize + 1]; 12 | int freq, next; 13 | } WordInfo; 14 | 15 | int main() { 16 | int getWord(FILE *, char[]); 17 | void printResults(FILE *, WordInfo [], int); 18 | int search(WordInfo [], char []); 19 | int addToTable(WordInfo [], char [], int, int); 20 | char word[MaxWordSize+1]; 21 | WordInfo wordTable[N+1]; //N - table size 22 | 23 | for (int h = 1; h <= N; h++) strcpy(wordTable[h].word, Empty); 24 | 25 | FILE * in = fopen("wordFreq.in", "r"); 26 | FILE * out = fopen("wordFreq.out", "w"); 27 | 28 | int first = -1; //points to first word in alphabetical order 29 | int numWords = 0; 30 | 31 | while (getWord(in, word) != 0) { 32 | int loc = search(wordTable, word); 33 | if (loc > 0) wordTable[loc].freq++; 34 | else //this is a new word 35 | if (numWords < MaxWords) { //if table is not full 36 | first = addToTable(wordTable, word, -loc, first); 37 | ++numWords; 38 | } 39 | else fprintf(out, "'%s' not added to table\n", word); 40 | } 41 | printResults(out, wordTable, first); 42 | fclose(in); 43 | fclose(out); 44 | } // end main 45 | 46 | int getWord(FILE * in, char str[]) { 47 | // stores the next word, if any, in str; word is converted to lowercase 48 | // returns 1 if a word is found; 0, otherwise 49 | char ch; 50 | int n = 0; 51 | // read over non-letters 52 | while (!isalpha(ch = getc(in)) && ch != EOF) ; //empty while body 53 | if (ch == EOF) return 0; 54 | str[n++] = tolower(ch); 55 | while (isalpha(ch = getc(in)) && ch != EOF) 56 | if (n < MaxWordSize) str[n++] = tolower(ch); 57 | str[n] = '\0'; 58 | return 1; 59 | } // end getWord 60 | 61 | int search(WordInfo table[], char key[]) { 62 | //search for key in table; if found, return its location; if not, 63 | //return -loc if it must be inserted in location loc 64 | int convertToNumber(char []); 65 | int keyNum = convertToNumber(key); 66 | int loc = keyNum % N + 1; 67 | int k = keyNum % (N - 2) + 1; 68 | 69 | while ((strcmp(table[loc].word, Empty) != 0) && 70 | (strcmp(table[loc].word, key) != 0)) { 71 | loc = loc + k; 72 | if (loc > N) loc = loc - N; 73 | } 74 | if (strcmp(table[loc].word, Empty) == 0) return -loc; 75 | return loc; 76 | } // end search 77 | 78 | int convertToNumber(char key[]) { 79 | int h = 0, keyNum = 0, w = 3; 80 | while (key[h] != '\0') { 81 | keyNum += w * key[h++]; 82 | w = w + 2; 83 | } 84 | return keyNum; 85 | } //end convertToNumber 86 | 87 | int addToTable(WordInfo table[], char key[], int loc, int head) { 88 | //stores key in table[loc] and links it in alphabetical order 89 | strcpy(table[loc].word, key); 90 | table[loc].freq = 1; 91 | int curr = head; 92 | int prev = -1; 93 | while (curr != -1 && (strcmp(key, table[curr].word) > 0)) { 94 | prev = curr; 95 | curr = table[curr].next; 96 | } 97 | table[loc].next = curr; 98 | if (prev == -1) return loc; //new first item 99 | table[prev].next = loc; 100 | return head; //first item did not change 101 | } //end addToTable 102 | 103 | void printResults(FILE *out, WordInfo table[], int head) { 104 | fprintf(out, "\nWords Frequency\n\n"); 105 | while (head != -1) { 106 | fprintf(out, "%-15s %2d\n", table[head].word, table[head].freq); 107 | head = table[head].next; 108 | } 109 | } //end printResults 110 | -------------------------------------------------------------------------------- /P11SelectionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MaxNumbers 10 3 | int main() { 4 | void selectionSort(int [], int, int); 5 | int num[MaxNumbers]; 6 | printf("Type up to %d numbers followed by 0\n", MaxNumbers); 7 | int n = 0, v; 8 | scanf("%d", &v); 9 | while (v != 0 && n < MaxNumbers) { 10 | num[n++] = v; 11 | scanf("%d", &v); 12 | } 13 | if (v != 0) { 14 | printf("More than %d numbers entered\n", MaxNumbers); 15 | printf("First %d used\n", MaxNumbers); 16 | } 17 | //n numbers are stored from num[0] to num[n-1] 18 | selectionSort(num, 0, n-1); 19 | printf("\nThe sorted numbers are\n"); 20 | for (int h = 0; h < n; h++) printf("%d ", num[h]); 21 | printf("\n"); 22 | } 23 | 24 | void selectionSort(int list[], int lo, int hi) { 25 | //sort list[lo] to list[hi] in ascending order 26 | int getSmallest(int[], int, int); 27 | void swap(int[], int, int); 28 | for (int h = lo; h < hi; h++) { 29 | int s = getSmallest(list, h, hi); 30 | swap(list, h, s); 31 | } 32 | } 33 | 34 | int getSmallest(int list[], int lo, int hi) { 35 | //return location of smallest from list[lo..hi] 36 | int small = lo; 37 | for (int h = lo + 1; h <= hi; h++) 38 | if (list[h] < list[small]) small = h; 39 | return small; 40 | } 41 | 42 | void swap(int list[], int i, int j) { 43 | //swap elements list[i] and list[j] 44 | int hold = list[i]; 45 | list[i] = list[j]; 46 | list[j] = hold; 47 | } 48 | -------------------------------------------------------------------------------- /P12InsertionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MaxNumbers 10 3 | int main() { 4 | void insertionSort(int [], int); 5 | void insertionSort1(int [], int, int); 6 | void insertionSort2(int [], int, int); 7 | int num[MaxNumbers]; 8 | printf("Type up to %d numbers followed by 0\n", MaxNumbers); 9 | int n = 0, v; 10 | scanf("%d", &v); 11 | while (v != 0 && n < MaxNumbers) { 12 | num[n++] = v; 13 | scanf("%d", &v); 14 | } 15 | if (v != 0) { 16 | printf("More than %d numbers entered\n", MaxNumbers); 17 | printf("First %d used\n", MaxNumbers); 18 | } 19 | //n numbers are stored from num[0] to num[n-1] 20 | insertionSort2(num, 0, n-1); 21 | printf("\nThe sorted numbers are\n"); 22 | for (int h = 0; h < n; h++) printf("%d ", num[h]); 23 | printf("\n"); 24 | } 25 | 26 | 27 | void insertionSort(int list[], int n) { 28 | //sort list[0] to list[n-1] in ascending order 29 | for (int h = 1; h < n; h++) { 30 | int key = list[h]; 31 | int k = h - 1; //start comparing with previous item 32 | while (k >= 0 && key < list[k]) { 33 | list[k + 1] = list[k]; 34 | --k; 35 | } 36 | list[k + 1] = key; 37 | } //end for 38 | } //end insertionSort 39 | 40 | 41 | void insertionSort1(int list[], int lo, int hi) { 42 | //sort list[lo] to list[hi] in ascending order 43 | for (int h = lo + 1; h <= hi; h++) { 44 | int key = list[h]; 45 | int k = h - 1; //start comparing with previous item 46 | while (k >= lo && key < list[k]) { 47 | list[k + 1] = list[k]; 48 | --k; 49 | } 50 | list[k + 1] = key; 51 | } //end for 52 | } //end insertionSort1 53 | 54 | void insertInPlace(int newItem, int list[], int m, int n) { 55 | //list[m] to list[n] are sorted 56 | //insert newItem so that list[m] to list[n+1] are sorted 57 | int k = n; 58 | while (k >= m && newItem < list[k]) { 59 | list[k + 1] = list[k]; 60 | --k; 61 | } 62 | list[k + 1] = newItem; 63 | } //end insertInPlace 64 | 65 | 66 | void insertionSort2(int list[], int lo, int hi) { 67 | //sort list[lo] to list[hi] in ascending order 68 | void insertInPlace(int, int [], int, int); 69 | for (int h = lo + 1; h <= hi; h++) 70 | insertInPlace(list[h], list, lo, h - 1); 71 | } //end insertionSort2 72 | 73 | 74 | -------------------------------------------------------------------------------- /P13StringInsertionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MaxNameSize 14 4 | #define MaxNameBuffer MaxNameSize+1 5 | #define MaxNames 8 6 | int main() { 7 | void insertionSort3(int, int, int max, char [][max]); 8 | char name[MaxNames][MaxNameBuffer] = {"Taylor, Victor", "Duncan, Denise", 9 | "Ramdhan, Kamal", "Singh, Krishna", "Ali, Michael", 10 | "Sawh, Anisa", "Khan, Carol", "Owen, David" }; 11 | 12 | insertionSort3(0, MaxNames-1, MaxNameBuffer, name); 13 | printf("\nThe sorted names are\n\n"); 14 | for (int h = 0; h < MaxNames; h++) printf("%s\n", name[h]); 15 | } //end main 16 | 17 | void insertionSort3(int lo, int hi, int max, char list[][max]) { 18 | //Sort the strings in list[lo] to list[hi] in alphabetical order. 19 | //The maximum string size is max - 1 (one char taken up by \0). 20 | char key[max]; 21 | for (int h = lo + 1; h <= hi; h++) { 22 | strcpy(key, list[h]); 23 | int k = h - 1; //start comparing with previous item 24 | while (k >= lo && strcmp(key, list[k]) < 0) { 25 | strcpy(list[k + 1], list[k]); 26 | --k; 27 | } 28 | strcpy(list[k + 1], key); 29 | } //end for 30 | } // end insertionSort3 31 | -------------------------------------------------------------------------------- /P14BinarySearchString.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MaxNameSize 14 4 | #define MaxNameBuffer MaxNameSize+1 5 | #define MaxNames 8 6 | int main () { 7 | int binarySearch(int, int, char [], int max, char [][max]); 8 | int n; 9 | char name[MaxNames][MaxNameBuffer] = {"Ali, Michael","Duncan, Denise", 10 | "Khan, Carol","Owen, David", "Ramdhan, Kamal", 11 | "Sawh, Anisa", "Singh, Krishna", "Taylor, Victor"}; 12 | n = binarySearch(0, 7, "Ali, Michael", MaxNameBuffer, name); 13 | printf("%d\n", n); //will print 0, location of Ali, Michael 14 | n = binarySearch(0, 7, "Taylor, Victor", MaxNameBuffer, name); 15 | printf("%d\n", n); //will print 7, location of Taylor, Victor 16 | n = binarySearch(0, 7, "Owen, David", MaxNameBuffer, name); 17 | printf("%d\n", n); //will print 3, location of Owen, David 18 | n = binarySearch(4, 7, "Owen, David", MaxNameBuffer, name); 19 | printf("%d\n", n); //will print -1, since Owen, David is not in locations 4 to 7 20 | n = binarySearch(0, 7, "Sandy, Cindy", MaxNameBuffer, name); 21 | printf("%d\n", n); //will print -1 since Sandy, Cindy is not in the list 22 | } //end main 23 | 24 | int binarySearch(int lo, int hi, char key[], int max, char list[][max]) { 25 | //search for key from list[lo] to list[hi] 26 | //if found, return its location; otherwise, return -1 27 | while (lo <= hi) { 28 | int mid = (lo + hi) / 2; 29 | int cmp = strcmp(key, list[mid]); 30 | if (cmp == 0) return mid; // found 31 | if (cmp < 0) hi = mid - 1; 32 | else lo = mid + 1; 33 | } 34 | return -1; //lo and hi have crossed; key not found 35 | } //end binarySearch 36 | -------------------------------------------------------------------------------- /P15WordFrequency.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MaxWords 50 6 | #define MaxLength 10 7 | #define MaxWordBuffer MaxLength+1 8 | int main() { 9 | int getWord(FILE *, char[]); 10 | int binarySearch(int, int, char [], int max, char [][max]); 11 | void addToList(char[], int max, char [][max], int[], int, int); 12 | void printResults(FILE *, int max, char [][max], int[], int); 13 | char wordList[MaxWords][MaxWordBuffer], word[MaxWordBuffer]; 14 | int frequency[MaxWords], numWords = 0; 15 | 16 | FILE * in = fopen("passage.txt", "r"); 17 | if (in == NULL){ 18 | printf("Cannot find file\n"); 19 | exit(1); 20 | } 21 | 22 | FILE * out = fopen("output.txt", "w"); 23 | if (out == NULL){ 24 | printf("Cannot create output file\n"); 25 | exit(2); 26 | } 27 | 28 | for (int h = 1; h <= MaxWords ; h++) frequency[h] = 0; 29 | 30 | while (getWord(in, word) != 0) { 31 | int loc = binarySearch (0, numWords-1, word, MaxWordBuffer, wordList); 32 | if (strcmp(word, wordList[loc]) == 0) ++frequency[loc]; //word found 33 | else //this is a new word 34 | if (numWords < MaxWords) { //if table is not full 35 | addToList(word, MaxWordBuffer, wordList, frequency, loc, numWords-1); 36 | ++numWords; 37 | } 38 | else fprintf(out, "'%s' not added to table\n", word); 39 | } 40 | printResults(out, MaxWordBuffer, wordList, frequency, numWords); 41 | } // end main 42 | 43 | int getWord(FILE * in, char str[]) { 44 | // stores the next word, if any, in str; word is converted to lowercase 45 | // returns 1 if a word is found; 0, otherwise 46 | char ch; 47 | int n = 0; 48 | // read over white space 49 | while (!isalpha(ch = getc(in)) && ch != EOF) ; //empty while body 50 | if (ch == EOF) return 0; 51 | str[n++] = tolower(ch); 52 | while (isalpha(ch = getc(in)) && ch != EOF) 53 | if (n < MaxLength) str[n++] = tolower(ch); 54 | str[n] = '\0'; 55 | return 1; 56 | } // end getWord 57 | 58 | int binarySearch(int lo, int hi, char key[], int max, char list[][max]) { 59 | //search for key from list[lo] to list[hi] 60 | //if found, return its location; 61 | //if not found, return the location in which it should be inserted 62 | //the calling program will check the location to determine if found 63 | while (lo <= hi) { 64 | int mid = (lo + hi) / 2; 65 | int cmp = strcmp(key, list[mid]); 66 | if (cmp == 0) return mid; // found 67 | if (cmp < 0) hi = mid - 1; 68 | else lo = mid + 1; 69 | } 70 | return lo; //not found; should be inserted in location lo 71 | } //end binarySearch 72 | 73 | void addToList(char item[], int max, char list[][max], int freq[], int p, int n) { 74 | //adds item in position list[p]; sets freq[p] to 1 75 | //shifts list[n] down to list[p] to the right 76 | for (int h = n; h >= p; h--) { 77 | strcpy(list[h+1], list[h]); 78 | freq[h+1] = freq[h]; 79 | } 80 | strcpy(list[p], item); 81 | freq[p] = 1; 82 | } //end addToList 83 | 84 | void printResults(FILE *out, int max, char list[][max], int freq[], int n) { 85 | fprintf(out, "\nWords Frequency\n\n"); 86 | for (int h = 0; h < n; h++) 87 | fprintf(out, "%-15s %2d\n", list[h], freq[h]); 88 | } //end printResults 89 | -------------------------------------------------------------------------------- /P1xMerge.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main () { 3 | int merge(int[], int, int[], int, int[]); 4 | int A[] = {21, 28, 35, 40, 61, 75}; 5 | int B[] = {16, 25, 47, 54}; 6 | int C[20]; 7 | int n = merge(A, 6 , B, 4, C); 8 | for (int h = 0; h < n; h++) printf("%d ", C[h]); 9 | printf("\n\n"); 10 | } //end main 11 | 12 | int merge(int A[], int m, int B[], int n, int C[]) { 13 | int i = 0; //i points to the first (smallest) number in A 14 | int j = 0; //j points to the first (smallest) number in B 15 | int k = -1; //k will be incremented before storing a number in C[k] 16 | while (i < m && j < n) { 17 | if (A[i] < B[j]) C[++k] = A[i++]; 18 | else C[++k] = B[j++]; 19 | } 20 | if (i == m) ///copy B[j] to B[n-1] to C 21 | for ( ; j < n; j++) C[++k] = B[j]; 22 | else // j == n, copy A[i] to A[m-1] to C 23 | for ( ; i < m; i++) C[++k] = A[i]; 24 | return m + n; 25 | } //end merge 26 | -------------------------------------------------------------------------------- /P1xParallelSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MaxNameSize 14 4 | #define MaxNameBuffer MaxNameSize+1 5 | #define MaxNames 8 6 | int main() { 7 | void parallelSort(int, int, int max, char [][max], int[]); 8 | char name[MaxNames][MaxNameBuffer] = {"Taylor, Victor", "Duncan, Denise", 9 | "Ramdhan, Kamal", "Singh, Krishna", "Ali, Michael", 10 | "Sawh, Anisa", "Khan, Carol", "Owen, David" }; 11 | int id[MaxNames] = {3050,2795,4455,7824,6669,5000,5464,6050}; 12 | 13 | parallelSort(0, MaxNames-1, MaxNameBuffer, name, id); 14 | printf("\nThe sorted names and IDs are\n\n"); 15 | for (int h = 0; h < MaxNames; h++) printf("%-18s %d\n", name[h], id[h]); 16 | } //end main 17 | 18 | void parallelSort(int lo, int hi, int max, char list[][max], int id[]) { 19 | //Sort the names in list[lo] to list[hi] in alphabetical order, ensuring that 20 | //each name remains with its original id number. 21 | //The maximum string size is max - 1 (one char taken up by \0). 22 | char key[max]; 23 | for (int h = lo + 1; h <= hi; h++) { 24 | strcpy(key, list[h]); 25 | int m = id[h]; // extract the id number 26 | int k = h - 1; //start comparing with previous item 27 | while (k >= lo && strcmp(key, list[k]) < 0) { 28 | strcpy(list[k + 1], list[k]); 29 | id[k+ 1] = id[k]; // move up id number when we move a name 30 | --k; 31 | } 32 | strcpy(list[k + 1], key); 33 | id[k + 1] = m; // store the id number in the same position as the name 34 | } //end for 35 | } //end parallelSort 36 | -------------------------------------------------------------------------------- /P21SortSearchStruct.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MaxStudents 100 6 | #define MaxNameLength 30 7 | #define MaxNameBuffer MaxNameLength+1 8 | typedef struct { 9 | char name[MaxNameBuffer]; 10 | int age; 11 | char gender; 12 | } Student; 13 | 14 | int main() { 15 | Student pupil[MaxStudents]; 16 | char aName[MaxNameBuffer]; 17 | void getString(FILE *, char[]); 18 | int getData(FILE *, Student[]); 19 | int search(char[], Student[], int); 20 | void sort(Student[], int); 21 | void printStudent(Student); 22 | void getString(FILE *, char[]); 23 | 24 | FILE * in = fopen("input.txt", "r"); 25 | if (in == NULL) { 26 | printf("Error opening file: %s.\n", strerror(errno)); 27 | exit(1); 28 | } 29 | 30 | int numStudents = getData(in, pupil); 31 | if (numStudents == 0) { 32 | printf("No data supplied for students"); 33 | exit(1); 34 | } 35 | 36 | printf("\n"); 37 | for (int h = 0; h < numStudents; h++) printStudent(pupil[h]); 38 | printf("\n"); 39 | 40 | getString(in, aName); 41 | while (strcmp(aName, "END") != 0) { 42 | int ans = search(aName, pupil, numStudents); 43 | if (ans == -1) printf("%s not found\n", aName); 44 | else printf("%s found at location %d\n", aName, ans); 45 | getString(in, aName); 46 | } 47 | 48 | sort(pupil, numStudents); 49 | printf("\n"); 50 | for (int h = 0; h < numStudents; h++) printStudent(pupil[h]); 51 | } //end main 52 | 53 | void printStudent(Student t) { 54 | printf("Name: %s Age: %d Gender: %c\n", t.name, t.age, t.gender); 55 | } //end printStudent 56 | 57 | int getData(FILE *in, Student list[]) { 58 | char temp[MaxNameBuffer]; 59 | void getString(FILE *, char[]); 60 | char readChar(FILE *); 61 | 62 | int n = 0; 63 | getString(in, temp); 64 | while (n < MaxStudents && strcmp(temp, "END") != 0) { 65 | strcpy(list[n].name, temp); 66 | fscanf(in, "%d", &list[n].age); 67 | list[n].gender = readChar(in); 68 | n++; 69 | getString(in, temp); 70 | } 71 | return n; 72 | } //end getData 73 | 74 | int search(char key[], Student list[], int n) { 75 | //search for key in list[0] to list[n-1] 76 | //if found, return the location; if not found, return -1 77 | for (int h = 0; h < n; h++) 78 | if (strcmp(key, list[h].name) == 0) return h; 79 | return -1; 80 | } //end search 81 | 82 | void sort(Student list[], int n) { 83 | //sort list[0] to list[n-1] by name using an insertion sort 84 | for (int h = 1; h < n; h++) { 85 | Student temp = list[h]; 86 | int k = h - 1; 87 | while (k >= 0 && strcmp(temp.name, list[k].name) < 0) { 88 | list[k + 1] = list[k]; 89 | k = k - 1; 90 | } 91 | list[k + 1] = temp; 92 | } //end for 93 | } //end sort 94 | 95 | void getString(FILE * in, char str[]) { 96 | //stores, in str, the next string within delimiters 97 | // the first non-whitespace character is the delimiter 98 | // the string is read from the file 'in' 99 | 100 | char ch, delim; 101 | int n = 0; 102 | str[0] = '\0'; 103 | // read over white space 104 | while (isspace(ch = getc(in))) ; //empty while body 105 | if (ch == EOF) return; 106 | 107 | delim = ch; 108 | while (((ch = getc(in)) != delim) && (ch != EOF)) 109 | str[n++] = ch; 110 | str[n] = '\0'; 111 | } // end getString 112 | 113 | char readChar(FILE * in) { 114 | char ch; 115 | while (isspace(ch = getc(in))) ; //empty while body 116 | return ch; 117 | } //end readChar 118 | -------------------------------------------------------------------------------- /P2xVoting.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MaxCandidates 7 4 | #define MaxNameLength 30 5 | #define MaxNameBuffer MaxNameLength+1 6 | 7 | typedef struct { 8 | char name[MaxNameBuffer]; 9 | int numVotes; 10 | } PersonData; 11 | PersonData candidate[MaxCandidates]; 12 | 13 | typedef struct { 14 | int valid, spoilt; 15 | } VoteCount; 16 | 17 | int main() { 18 | void initialize(PersonData[], int, FILE *); 19 | VoteCount processVotes(PersonData[], int, FILE *, FILE *); 20 | void printResults(PersonData[], int, VoteCount, FILE *); 21 | 22 | PersonData candidate[MaxCandidates+1]; 23 | VoteCount count; 24 | FILE *in = fopen("votes.txt", "r"); 25 | FILE *out = fopen("results.txt", "w"); 26 | 27 | initialize(candidate, MaxCandidates, in); 28 | count = processVotes(candidate, MaxCandidates, in, out); 29 | // sortByVote(candidate, 1, MaxCandidates); 30 | // sortByName(candidate, 1, MaxCandidates); 31 | printResults(candidate, MaxCandidates, count, out); 32 | 33 | fclose(in); 34 | fclose(out); 35 | } //end main 36 | 37 | void initialize(PersonData person[], int max, FILE *in) { 38 | char lastName[MaxNameBuffer]; 39 | for (int h = 1; h <= max; h++) { 40 | fscanf(in, "%s %s", person[h].name, lastName); 41 | strcat(person[h].name, " "); 42 | strcat(person[h].name, lastName); 43 | person[h].numVotes = 0; 44 | } 45 | } //end initialize 46 | 47 | VoteCount processVotes(PersonData person[], int max, 48 | FILE *in, FILE *out) { 49 | VoteCount temp; 50 | temp.valid = temp.spoilt = 0; 51 | 52 | int v; 53 | fscanf(in, "%d", &v); 54 | while (v != 0) { 55 | if (v < 1 || v > max) { 56 | fprintf(out, "Invalid vote: %d\n", v); 57 | ++temp.spoilt; 58 | } 59 | else { 60 | ++person[v].numVotes; 61 | ++temp.valid; 62 | } 63 | fscanf(in, "%d", &v); 64 | } //end while 65 | return temp; 66 | } //end processVotes 67 | 68 | void printResults(PersonData person[], int max, VoteCount c, FILE *out) { 69 | int getLargest(PersonData[], int, int); 70 | fprintf(out, "\nNumber of voters: %d\n", c.valid + c.spoilt); 71 | fprintf(out, "Number of valid votes: %d\n", c.valid); 72 | fprintf(out, "Number of spoilt votes: %d\n", c.spoilt); 73 | fprintf(out, "\nCandidate Score\n\n"); 74 | 75 | for (int h = 1; h <= max; h++) 76 | fprintf(out, "%-15s %3d\n", person[h].name, person[h].numVotes); 77 | 78 | fprintf(out, "\nThe winner(s)\n"); 79 | int win = getLargest(person, 1, max); 80 | int winningVote = person[win].numVotes; 81 | for (int h = 1; h <= max; h++) 82 | if (person[h].numVotes == winningVote) 83 | fprintf(out, "%s\n", person[h].name); 84 | } //end printResults 85 | 86 | int getLargest(PersonData person[], int lo, int hi) { 87 | //returns the index of the highest vote from person[lo] to person[hi] 88 | int big = lo; 89 | for (int h = lo + 1; h <= hi; h++) 90 | if (person[h].numVotes > person[big].numVotes) big = h; 91 | return big; 92 | } //end getLargest 93 | 94 | void sortByVote(PersonData person[], int lo, int hi) { 95 | //sort person[lo..hi] in descending order by numVotes 96 | PersonData insertItem; 97 | for (int h = lo + 1; h <= hi; h++) { // process person[lo+1] to person[hi] 98 | // insert person h in its proper position 99 | insertItem = person[h]; 100 | int k = h -1; 101 | while (k >= lo && insertItem.numVotes > person[k].numVotes) { 102 | person[k + 1] = person[k]; 103 | --k; 104 | } 105 | person[k + 1] = insertItem; 106 | } 107 | } //end sortByVote 108 | 109 | void sortByName(PersonData person[], int lo, int hi) { 110 | //sort person[lo..hi] in alphabetical order by name 111 | PersonData insertItem; 112 | for (int h = lo + 1; h <= hi; h++) { // process person[lo+1] to person[hi] 113 | // insert person j in its proper position 114 | insertItem = person[h]; 115 | int k = h -1; 116 | while (k > 0 && strcmp(insertItem.name, person[k].name) < 0) { 117 | person[k + 1] = person[k]; 118 | --k; 119 | } 120 | person[k + 1] = insertItem; 121 | } 122 | } //end sortByName 123 | -------------------------------------------------------------------------------- /P31Test.c: -------------------------------------------------------------------------------- 1 | // Program P3.1 2 | 3 | #include 4 | int main() { 5 | void test(int); 6 | int n = 14; 7 | printf("%d\n", n); // before calling test 8 | test(n); 9 | printf("%d\n", n); // after return from test 10 | } //end main 11 | 12 | void test(int a) { 13 | a = a + 6; 14 | printf("%d\n", a); // within test 15 | } //end test 16 | -------------------------------------------------------------------------------- /P32Test.c: -------------------------------------------------------------------------------- 1 | // Program P3.2 2 | 3 | #include 4 | int main() { 5 | void test(int *); 6 | int n = 14; 7 | printf("%d\n", n); // before calling test 8 | test(&n); 9 | printf("%d\n", n); // after return from test 10 | } //end main 11 | 12 | void test(int *a) { 13 | *a = *a + 6; 14 | printf("%d\n", *a); // within test 15 | } //end test 16 | 17 | -------------------------------------------------------------------------------- /P33Test.c: -------------------------------------------------------------------------------- 1 | //Program P3.3 2 | 3 | #include 4 | int main() { 5 | void test(int val[], int max); 6 | int list[5]; 7 | 8 | for (int h = 0; h < 5; h++) list[h] = h; 9 | test(list, 5); 10 | for (int h = 0; h < 5; h++) printf("%d ", list[h]); 11 | printf("\n"); 12 | } //end main 13 | 14 | void test(int val[], int max) { 15 | // add 25 to each of val[0] to val[max - 1] 16 | for (int h = 0; h < max; h++) val[h] += 25; 17 | } //end test 18 | -------------------------------------------------------------------------------- /P34Function.c: -------------------------------------------------------------------------------- 1 | // Program P3.4 2 | 3 | #include 4 | int main() { 5 | void makeTable(int, int, double (*fp) (int)); 6 | double reciprocal(int); 7 | double square(int); 8 | makeTable(1, 10, reciprocal); 9 | } //end main 10 | 11 | void makeTable(int first, int last, double (*fp) (int)) { 12 | for (int h = first; h <= last; h++) 13 | printf("%2d %0.3f\n", h, (*fp)(h)); 14 | } //end makeTable 15 | 16 | double reciprocal(int x) { 17 | return 1.0 / x; 18 | } //end reciprocal 19 | 20 | double square(int x) { 21 | return x * x; 22 | } 23 | -------------------------------------------------------------------------------- /P41LLInOrder.c: -------------------------------------------------------------------------------- 1 | //Program P4.1 2 | 3 | #include 4 | #include 5 | typedef struct node { 6 | int num; 7 | struct node *next; 8 | } Node, *NodePtr; 9 | 10 | int main() { 11 | void printList(NodePtr); 12 | NodePtr makeNode(int); 13 | int n; 14 | NodePtr top, np, last; 15 | 16 | top = NULL; 17 | if (scanf("%d", &n) != 1) n = 0; 18 | while (n != 0) { 19 | np = makeNode(n); //create a new node containing n 20 | if (top == NULL) top = np; //set top if first node 21 | else last -> next = np; //set last -> next for other nodes 22 | last = np; //update last to new node 23 | if (scanf("%d", &n) != 1) n = 0; 24 | } 25 | printList(top); 26 | } //end main 27 | 28 | NodePtr makeNode(int n) { 29 | NodePtr np = (NodePtr) malloc(sizeof (Node)); 30 | np -> num = n; 31 | np -> next = NULL; 32 | return np; 33 | } //end makeNode 34 | 35 | void printList(NodePtr np) { 36 | while (np != NULL) { // as long as there's a node 37 | printf("%d\n", np -> num); 38 | np = np -> next; // go on to the next node 39 | } 40 | } //end printList 41 | -------------------------------------------------------------------------------- /P42LLReverseOrder.c: -------------------------------------------------------------------------------- 1 | // Program P4.2 2 | 3 | #include 4 | #include 5 | typedef struct node { 6 | int num; 7 | struct node *next; 8 | } Node, *NodePtr; 9 | 10 | //add new numbers at the head of the list 11 | int main() { 12 | void printList(NodePtr); 13 | NodePtr makeNode(int); 14 | int n; 15 | NodePtr top, np; 16 | top = NULL; 17 | if (scanf("%d", &n) != 1) n = 0; 18 | while (n != 0) { 19 | np = makeNode(n); //create a new node containing n 20 | np -> next = top; //set link of new node to first node 21 | top = np; //set top to point to new node 22 | if (scanf("%d", &n) != 1) n = 0; 23 | } 24 | printList(top); 25 | } //end main 26 | 27 | NodePtr makeNode(int n) { 28 | NodePtr np = (NodePtr) malloc(sizeof (Node)); 29 | np -> num = n; 30 | np -> next = NULL; 31 | return np; 32 | } //end makeNode 33 | 34 | void printList(NodePtr np) { 35 | while (np != NULL) { // as long as there's a node 36 | printf("%d\n", np -> num); 37 | np = np -> next; // go on to the next node 38 | } 39 | } //end printList 40 | -------------------------------------------------------------------------------- /P43LLSortedOrder.c: -------------------------------------------------------------------------------- 1 | // Program P4.3 2 | 3 | #include 4 | #include 5 | 6 | typedef struct node { 7 | int num; 8 | struct node *next; 9 | } Node, *NodePtr; 10 | 11 | int main() { 12 | void printList(NodePtr); 13 | NodePtr addInPlace(NodePtr, int); 14 | int n; 15 | NodePtr top = NULL; 16 | if (scanf("%d", &n) != 1) n = 0; 17 | while (n != 0) { 18 | top = addInPlace(top, n); 19 | if (scanf("%d", &n) != 1) n = 0; 20 | } 21 | printList(top); 22 | } //end main 23 | 24 | NodePtr addInPlace(NodePtr top, int n) { 25 | // This functions inserts n in its ordered position in a (possibly empty) 26 | // list pointed to by top, and returns a pointer to the new list 27 | NodePtr np, curr, prev, makeNode(int); 28 | 29 | np = makeNode(n); 30 | prev = NULL; 31 | curr = top; 32 | while (curr != NULL && n > curr -> num) { 33 | prev = curr; 34 | curr = curr -> next; 35 | } 36 | if (prev == NULL) { //new number must be added at the top 37 | np -> next = top; 38 | return np; //the top of the list has changed to the new node 39 | } 40 | np -> next = curr; 41 | prev -> next = np; 42 | return top; //the top of the list has not changed 43 | } //end addInPlace 44 | 45 | NodePtr makeNode(int n) { 46 | NodePtr np = (NodePtr) malloc(sizeof (Node)); 47 | np -> num = n; 48 | np -> next = NULL; 49 | return np; 50 | } // end makeNode 51 | 52 | void printList(NodePtr np) { 53 | while (np != NULL) { // as long as there's a node 54 | printf("%d\n", np -> num); 55 | np = np -> next; // go on to the next node 56 | } 57 | } //end printList 58 | -------------------------------------------------------------------------------- /P44Palindrome.c: -------------------------------------------------------------------------------- 1 | // Program P4.4 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | typedef struct node { 8 | char ch; 9 | struct node * next; 10 | } Node, *NodePtr; 11 | 12 | int main() { 13 | NodePtr getPhrase(); 14 | NodePtr reverseLetters(NodePtr); 15 | int compare(NodePtr, NodePtr); 16 | NodePtr phrase, s1, s2; 17 | 18 | printf("Type a phrase. (To stop, press 'Enter' only): "); 19 | phrase = getPhrase(); 20 | while (phrase != NULL) { 21 | s1 = reverseLetters(phrase); 22 | s2 = reverseLetters(s1); 23 | if (compare(s1, s2) == 0) printf("is a palindrome\n"); 24 | else printf("is not a palindrome\n"); 25 | printf("Type a word. (To stop, press 'Enter' only): "); 26 | phrase = getPhrase(); 27 | } 28 | } //end main 29 | 30 | NodePtr getPhrase() { 31 | NodePtr top = NULL, last, np; 32 | char c = getchar(); 33 | while (c != '\n') { 34 | np = (NodePtr) malloc(sizeof(Node)); 35 | np -> ch = c; 36 | np -> next = NULL; 37 | if (top == NULL) top = np; 38 | else last -> next = np; 39 | last = np; 40 | c = getchar(); 41 | } 42 | return top; 43 | } //end getPhrase 44 | 45 | NodePtr reverseLetters(NodePtr top) { 46 | NodePtr rev = NULL, np; 47 | char c; 48 | while (top != NULL) { 49 | c = top -> ch; 50 | if (isalpha(c)) { // add to new list 51 | np = (NodePtr) malloc(sizeof(Node)); 52 | np -> ch = tolower(c); 53 | np -> next = rev; 54 | rev = np; 55 | } 56 | top = top -> next; //go to next character of phrase 57 | } 58 | return rev; 59 | } //end reverseLetter 60 | 61 | int compare(NodePtr s1, NodePtr s2) { 62 | //return -1 if s1 < s2, +1 if s1 > s2 and 0 if s1 = s2 63 | while (s1 != NULL) { 64 | if (s1 -> ch < s2 -> ch) return -1; 65 | else if (s1 -> ch > s2 -> ch) return 1; 66 | s1 = s1 -> next; 67 | s2 = s2 -> next; 68 | } 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /P45MergeSortedLL.c: -------------------------------------------------------------------------------- 1 | // Program P4.5 2 | 3 | #include 4 | #include 5 | typedef struct node { 6 | int num; 7 | struct node *next; 8 | } Node, *NodePtr; 9 | 10 | int main() { 11 | void printList(NodePtr); 12 | NodePtr makeList(void); 13 | NodePtr merge(NodePtr, NodePtr); 14 | NodePtr A, B; 15 | 16 | printf("Enter numbers for the first list (0 to end)\n"); 17 | A = makeList(); 18 | printf("Enter numbers for the second list (0 to end)\n"); 19 | B = makeList(); 20 | printf("\nThe merged list is\n"); 21 | printList(merge(A, B)); 22 | } //end main 23 | 24 | NodePtr makeList() { 25 | NodePtr makeNode(int), np, top, last; 26 | int n; 27 | top = NULL; 28 | if (scanf("%d", &n) != 1) n = 0; 29 | while (n != 0) { 30 | np = makeNode(n); //create a new node containing n 31 | if (top == NULL) top = np; //set top if first node 32 | else last -> next = np; //set last -> next for other nodes 33 | last = np; //update last to new node 34 | if (scanf("%d", &n) != 1) n = 0; 35 | } 36 | return top; 37 | } //end makeList 38 | 39 | NodePtr makeNode(int n) { 40 | NodePtr np = (NodePtr) malloc(sizeof (Node)); 41 | np -> num = n; 42 | np -> next = NULL; 43 | return np; 44 | } //end makeNode 45 | 46 | void printList(NodePtr np) { 47 | while (np != NULL) { // as long as there's a node 48 | printf("%d ", np -> num); 49 | np = np -> next; // go on to the next node 50 | } 51 | printf("\n\n"); 52 | } //end printList 53 | 54 | NodePtr merge(NodePtr A, NodePtr B) { 55 | NodePtr C = NULL, last = NULL; 56 | if (A == NULL) return B; 57 | if (B == NULL) return A; 58 | //both lists are non-empty 59 | while (A != NULL && B != NULL) { 60 | if (A -> num < B -> num) { 61 | if (C == NULL) C = A; else last -> next = A; 62 | last = A; 63 | A = A -> next ; 64 | } 65 | else { 66 | if (C == NULL) C = B; else last -> next = B; 67 | last = B; 68 | B = B -> next ; 69 | } 70 | } //end while 71 | if (A == NULL) last -> next = B; 72 | else last -> next = A; 73 | return C; 74 | } //end merge 75 | -------------------------------------------------------------------------------- /P51ArrayStackReverseNum.c: -------------------------------------------------------------------------------- 1 | //Program P5.1 2 | 3 | #include 4 | #include 5 | #define RogueValue -9999 6 | #define MaxStack 10 7 | 8 | typedef struct { 9 | int top; 10 | int ST[MaxStack]; 11 | } StackType, *Stack; 12 | 13 | int main() { 14 | Stack initStack(); 15 | int empty(Stack); 16 | void push(Stack, int); 17 | int pop(Stack); 18 | int n; 19 | Stack S = initStack(); 20 | printf("Enter some integers, ending with 0\n"); 21 | scanf("%d", &n); 22 | while (n != 0) { 23 | push(S, n); 24 | scanf("%d", &n); 25 | } 26 | printf("Numbers in reverse order\n"); 27 | while (!empty(S)) 28 | printf("%d ", pop(S)); 29 | printf("\n"); 30 | } //end main 31 | 32 | Stack initStack() { 33 | Stack sp = (Stack) malloc(sizeof(StackType)); 34 | sp -> top = -1; 35 | return sp; 36 | } //end initStack 37 | 38 | int empty(Stack S) { 39 | return (S -> top == -1); 40 | } //end empty 41 | 42 | void push(Stack S, int n) { 43 | if (S -> top == MaxStack - 1) { 44 | printf("\nStack Overflow\n"); 45 | exit(1); 46 | } 47 | ++(S -> top); 48 | S -> ST[S -> top]= n; 49 | } //end push 50 | 51 | int pop(Stack S) { 52 | if (empty(S)) return RogueValue; 53 | int hold = S -> ST[S -> top]; 54 | --(S -> top); 55 | return hold; 56 | } //end pop 57 | -------------------------------------------------------------------------------- /P52LLStackReverseNum.c: -------------------------------------------------------------------------------- 1 | // Program P5.2 2 | 3 | #include 4 | #include 5 | #define RogueValue -9999 6 | 7 | typedef struct node { 8 | int num; 9 | struct node *next; 10 | } Node, *NodePtr; 11 | 12 | typedef struct stackType { 13 | NodePtr top; 14 | } StackType, *Stack; 15 | 16 | int main() { 17 | Stack initStack(); 18 | int empty(Stack); 19 | void push(Stack, int); 20 | int pop(Stack); 21 | int n; 22 | Stack S = initStack(); 23 | printf("Enter some integers, ending with 0\n"); 24 | scanf("%d", &n); 25 | while (n != 0) { 26 | push(S, n); 27 | scanf("%d", &n); 28 | } 29 | printf("Numbers in reverse order\n"); 30 | while (!empty(S)) 31 | printf("%d ", pop(S)); 32 | printf("\n"); 33 | } //end main 34 | 35 | Stack initStack() { 36 | Stack sp = (Stack) malloc(sizeof(StackType)); 37 | sp -> top = NULL; 38 | return sp; 39 | } 40 | 41 | int empty(Stack S) { 42 | return (S -> top == NULL); 43 | } 44 | 45 | void push(Stack S, int n) { 46 | NodePtr np = (NodePtr) malloc(sizeof(Node)); 47 | np -> num = n; 48 | np -> next = S -> top; 49 | S -> top = np; 50 | } 51 | 52 | int pop(Stack S) { 53 | if (empty(S)) return RogueValue; 54 | int hold = S -> top -> num; 55 | NodePtr temp = S -> top; 56 | S -> top = S -> top -> next; 57 | free(temp); 58 | return hold; 59 | } 60 | 61 | -------------------------------------------------------------------------------- /P53StackHeaderTest.c: -------------------------------------------------------------------------------- 1 | // Program P5.3 2 | // For this program to work, the file stack.h (contents shown below) 3 | // must be stored in the "include" folder of your compiler 4 | 5 | #include 6 | #include 7 | 8 | int main() { 9 | int n; 10 | Stack S = initStack(); 11 | printf("Enter some integers, ending with 0\n"); 12 | scanf("%d", &n); 13 | while (n != 0) { 14 | push(S, n); 15 | scanf("%d", &n); 16 | } 17 | printf("\nNumbers in reverse order\n"); 18 | while (!empty(S)) 19 | printf("%d ", pop(S)); 20 | printf("\n"); 21 | } 22 | 23 | // contents of stack.h, shown as comments. Uncomment to use. 24 | 25 | //#include 26 | //#define RogueValue -9999 27 | // 28 | //typedef struct node { 29 | // int num; 30 | // struct node *next; 31 | //} Node, *NodePtr; 32 | // 33 | //typedef struct stackType { 34 | // NodePtr top; 35 | //} StackType, *Stack; 36 | // 37 | //Stack initStack() { 38 | // Stack sp = (Stack) malloc(sizeof(StackType)); 39 | // sp -> top = NULL; 40 | // return sp; 41 | //} 42 | // 43 | //int empty(Stack S) { 44 | // return (S -> top == NULL); 45 | //} //end empty 46 | // 47 | //void push(Stack S, int n) { 48 | // NodePtr np = (NodePtr) malloc(sizeof(Node)); 49 | // np -> num = n; 50 | // np -> next = S -> top; 51 | // S -> top = np; 52 | //} //end push 53 | // 54 | //int pop(Stack S) { 55 | // if (empty(S)) return RogueValue; 56 | // int hold = S -> top -> num; 57 | // NodePtr temp = S -> top; 58 | // S -> top = S -> top -> next; 59 | // free(temp); 60 | // return hold; 61 | //} //end pop 62 | -------------------------------------------------------------------------------- /P54ReverseData.c: -------------------------------------------------------------------------------- 1 | //Program P5.4 2 | 3 | #include 4 | 5 | typedef struct { 6 | char ch; 7 | } StackData; 8 | 9 | #include 10 | 11 | int main() { 12 | StackData temp; 13 | char c; 14 | Stack S = initStack(); 15 | printf("Type some data and press Enter\n"); 16 | while ((c = getchar()) != '\n') { 17 | temp.ch = c; 18 | push(S, temp); 19 | } 20 | printf("\nData in reverse order\n"); 21 | while (!empty(S)) 22 | putchar(pop(S).ch); 23 | putchar('\n'); 24 | } //end main 25 | -------------------------------------------------------------------------------- /P55ConvertToBinary.c: -------------------------------------------------------------------------------- 1 | // Program P5.5 2 | 3 | #include 4 | 5 | typedef struct { 6 | int bit; 7 | } StackData; 8 | 9 | #include 10 | 11 | int main() { 12 | StackData temp; 13 | int n; 14 | Stack S = initStack(); 15 | printf("Enter a positive integer: "); 16 | scanf("%d", &n); 17 | while (n > 0) { 18 | temp.bit = n % 2; 19 | push(S, temp); 20 | n = n / 2; 21 | } 22 | printf("\nIts binary equivalent is "); 23 | while (!empty(S)) 24 | printf("%d", pop(S).bit); 25 | printf("\n"); 26 | } //end main 27 | -------------------------------------------------------------------------------- /P56InfixToPostfix.c: -------------------------------------------------------------------------------- 1 | // Program P5.6 2 | 3 | #include 4 | #include 5 | typedef struct { 6 | char ch; 7 | } StackData; 8 | 9 | #include 10 | 11 | int main() { 12 | int readConvert(char[]); 13 | void printPostfix(char[], int); 14 | char post[50]; 15 | 16 | int n = readConvert(post); 17 | printPostfix(post, n); 18 | } //end main 19 | 20 | int readConvert(char post[]) { 21 | char getToken(void), token, c; 22 | int precedence(char); 23 | StackData temp; 24 | int h = 0; 25 | Stack S = initStack(); 26 | printf("Type an infix expression and press Enter\n"); 27 | token = getToken(); 28 | while (token != '\n') { 29 | if (isdigit(token)) post[h++] = token; 30 | else if (token == '(') { 31 | temp.ch = token; 32 | push(S, temp); 33 | } 34 | else if (token == ')') 35 | while ((c = pop(S).ch) != '(') post[h++] = c; 36 | else { 37 | while (!empty(S) && 38 | precedence(peek(S).ch) >= precedence(token)) 39 | post[h++] = pop(S).ch; 40 | temp.ch = token; 41 | push(S, temp); 42 | } 43 | token = getToken(); 44 | } //end while 45 | while (!empty(S)) post[h++] = pop(S).ch; 46 | return h; //the size of the expression 47 | } //end readConvert 48 | 49 | void printPostfix(char post[], int n) { 50 | printf("\nThe postfix form is \n"); 51 | for (int h = 0; h < n; h++) printf("%c ", post[h]); 52 | printf("\n"); 53 | } //end printPostfix 54 | 55 | char getToken() { 56 | char ch; 57 | while ((ch = getchar()) == ' ') ; //empty body 58 | return ch; 59 | } //end getToken 60 | 61 | //int precedence(char c) { 62 | // if (c == '(') return 0; 63 | // if (c == '+' || c == '-') return 3; 64 | // if (c == '*' || c == '/') return 5; 65 | //} //end precedence 66 | 67 | int precedence(char c) { 68 | switch (c) { 69 | case '(': return 0; 70 | case '+': 71 | case '-': return 3; 72 | case '*': 73 | case '/': return 5; 74 | }//end switch 75 | } //end precedence 76 | 77 | -------------------------------------------------------------------------------- /P56xEvalExpression.c: -------------------------------------------------------------------------------- 1 | // Program P5.6 2 | 3 | #include 4 | #include 5 | typedef struct { 6 | char ch; 7 | int num; 8 | } StackData; 9 | 10 | #include 11 | 12 | int main() { 13 | int readConvert(char[]); 14 | void printPostfix(char[], int); 15 | int eval(char[], int); 16 | char post[50]; 17 | 18 | int n = readConvert(post); 19 | printPostfix(post, n); 20 | printf("\nIts value is %d\n", eval(post, n)); 21 | } //end main 22 | 23 | int readConvert(char post[]) { 24 | char getToken(void), token, c; 25 | int precedence(char); 26 | StackData temp; 27 | int h = 0; 28 | Stack S = initStack(); 29 | printf("Type an infix expression and press Enter\n"); 30 | token = getToken(); 31 | while (token != '\n') { 32 | if (isdigit(token)) post[h++] = token; 33 | else if (token == '(') { 34 | temp.ch = token; 35 | push(S, temp); 36 | } 37 | else if (token == ')') 38 | while ((c = pop(S).ch) != '(') post[h++] = c; 39 | else { 40 | while (!empty(S) && 41 | precedence(peek(S).ch) >= precedence(token)) 42 | post[h++] = pop(S).ch; 43 | temp.ch = token; 44 | push(S, temp); 45 | } 46 | token = getToken(); 47 | } //end while 48 | while (!empty(S)) post[h++] = pop(S).ch; 49 | return h; //the size of the expression 50 | } //end readConvert 51 | 52 | void printPostfix(char post[], int n) { 53 | printf("\nThe postfix form is \n"); 54 | for (int h = 0; h < n; h++) printf("%c ", post[h]); 55 | printf("\n"); 56 | } //end printPostfix 57 | 58 | char getToken() { 59 | char ch; 60 | while ((ch = getchar()) == ' ') ; //empty body 61 | return ch; 62 | } //end getToken 63 | 64 | //int precedence(char c) { 65 | // if (c == '(') return 0; 66 | // if (c == '+' || c == '-') return 3; 67 | // if (c == '*' || c == '/') return 5; 68 | //} //end precedence 69 | 70 | int precedence(char c) { 71 | switch (c) { 72 | case '(': return 0; 73 | case '+': 74 | case '-': return 3; 75 | case '*': 76 | case '/': return 5; 77 | }//end switch 78 | } //end precedence 79 | 80 | int eval(char post[], int n) { 81 | int a, b, c; 82 | StackData temp; 83 | 84 | Stack S = initStack(); 85 | for (int h = 0; h < n; h++) { 86 | if (isdigit(post[h])) { 87 | temp.num = post[h] - '0'; //convert to integer 88 | push(S, temp); 89 | } 90 | else { 91 | b = pop(S).num; 92 | a = pop(S).num; 93 | if (post[h] == '+') c = a + b; 94 | else if (post[h] == '-') c = a - b; 95 | else if (post[h] == '*') c = a * b; 96 | else c = a / b; 97 | temp.num = c; 98 | push(S, temp); 99 | } 100 | } //end for 101 | return pop(S).num; 102 | } //end eval 103 | 104 | 105 | -------------------------------------------------------------------------------- /P57ReverseInteger.c: -------------------------------------------------------------------------------- 1 | // Program P5.7 2 | 3 | #include 4 | #define MaxQ 10 5 | #include 6 | 7 | main() { 8 | int n; 9 | Queue Q = initQueue(); 10 | printf("Enter a positive integer: "); 11 | scanf("%d", &n); 12 | while (n > 0) { 13 | enqueue(Q, n % 10); 14 | n = n / 10; 15 | } 16 | printf("\nDigits in reverse order: "); 17 | while (!empty(Q)) 18 | printf("%d", dequeue(Q)); 19 | printf("\n"); 20 | } 21 | -------------------------------------------------------------------------------- /P58ReverseIntegerLLQ.c: -------------------------------------------------------------------------------- 1 | // Program P5.8 2 | 3 | #include 4 | typedef struct { 5 | int num; 6 | } QueueData; 7 | #include 8 | 9 | main() { 10 | int n; 11 | QueueData temp; 12 | Queue Q = initQueue(); 13 | printf("Enter a positive integer: "); 14 | scanf("%d", &n); 15 | while (n > 0) { 16 | temp.num = n % 10; 17 | enqueue(Q, temp); 18 | n = n / 10; 19 | } 20 | printf("\nDigits in reverse order: "); 21 | while (!empty(Q)) 22 | printf("%d", dequeue(Q).num); 23 | printf("\n"); 24 | } //end main 25 | -------------------------------------------------------------------------------- /P61Organisms.c: -------------------------------------------------------------------------------- 1 | // Program P6.1 2 | #include 3 | #define MaxRow 20 4 | #define MaxCol 20 5 | 6 | int G[MaxRow][MaxCol]; 7 | int orgCount = 0; 8 | 9 | int main() { 10 | void findOrg(int, int, int, int); 11 | void printOrg(FILE *, int m, int n); 12 | int i, j, m, n; 13 | FILE * in = fopen("cell.in", "r"); 14 | FILE * out = fopen("cell.out", "w"); 15 | fscanf(in, "%d %d", &m, &n); 16 | for (i = 0; i < m; i++) 17 | for (j = 0; j < n; j++) 18 | fscanf(in, "%d", &G[i][j]); 19 | 20 | for (i = 0; i < m; i++) 21 | for (j = 0; j < n; j++) 22 | if (G[i][j] == 1) { 23 | orgCount++; 24 | findOrg(i, j, m, n); 25 | } 26 | 27 | printOrg(out, m, n); 28 | } //end main 29 | 30 | void findOrg(int i, int j, int m, int n) { 31 | if (i < 0 || i >= m || j < 0 || j >= n) return; //outside of grid 32 | if (G[i][j] == 0 || G[i][j] > 1) return; //no cell or cell already seen 33 | // else G[i][j] = 1; 34 | G[i][j]= orgCount + 1; //so that this 1 is not considered again 35 | findOrg(i - 1, j, m, n); 36 | findOrg(i, j + 1, m, n); 37 | findOrg(i + 1, j, m, n); 38 | findOrg(i, j - 1, m, n); 39 | } //end findOrg 40 | 41 | void printOrg(FILE * out, int m, int n) { 42 | int i, j; 43 | fprintf(out, "\nNumber of organisms = %d\n", orgCount); 44 | fprintf(out, "\nPosition of organisms are shown here\n\n"); 45 | for (i = 0; i < m; i++) { 46 | for (j = 0; j < n; j++) 47 | if (G[i][j] > 1) fprintf(out, "%2d ", G[i][j] - 1); 48 | //organism labels are one more than they should be 49 | else fprintf(out, "%2d ", G[i][j]); 50 | fprintf(out, "\n"); 51 | } 52 | } //end printOrg 53 | -------------------------------------------------------------------------------- /P62Maze.c: -------------------------------------------------------------------------------- 1 | // Program P6.2 2 | #include 3 | #define MaxRow 20 4 | #define MaxCol 20 5 | 6 | int m, n, sr, sc; 7 | int G[MaxRow+1][MaxCol+1]; 8 | 9 | main() { 10 | void getData(FILE *); 11 | int findPath(int, int); 12 | void printMaze(FILE *); 13 | 14 | FILE * in = fopen("maze.in", "r"); 15 | FILE * out = fopen("maze.out", "w"); 16 | 17 | getData(in); 18 | if (findPath(sr, sc)) printMaze(out); 19 | else fprintf(out, "\nNo solution\n"); 20 | 21 | fclose(in); 22 | fclose(out); 23 | } //end main 24 | 25 | void getData(FILE * in) { 26 | int r, c; 27 | fscanf(in, "%d %d %d %d", &m, &n, &sr, &sc); 28 | for (r = 1; r <= m; r++) 29 | for (c = 1; c <= n; c++) 30 | fscanf(in, "%d", &G[r][c]); 31 | } //end getData 32 | 33 | int findPath(int r, int c) { 34 | if (r < 1 || r > m || c < 1 || c > n) return 0; 35 | if (G[r][c] == 1) return 0; //into a wall 36 | if (G[r][c] == 2) return 0; //already considered 37 | 38 | // else G[r][c] = 0; 39 | G[r][c] = 2; //mark the path 40 | if (r == 1 || r == m || c == 1 || c == n) return 1; 41 | //path found - space located on the border of the maze 42 | 43 | if (findPath(r-1, c)) return 1; 44 | if (findPath(r, c+1)) return 1; 45 | if (findPath(r+1, c)) return 1; 46 | if (findPath(r, c-1)) return 1; 47 | G[r][c] = 0; //no path found; unmark 48 | return 0; 49 | } //end findPath 50 | 51 | void printMaze(FILE * out) { 52 | int r, c; 53 | for (r = 1; r <= m; r++) { 54 | for (c = 1; c <= n; c++) 55 | if (r == sr && c == sc) fprintf(out,"S"); 56 | else if (G[r][c] == 0) fprintf(out," "); 57 | else if (G[r][c] == 1) fprintf(out,"#"); 58 | else fprintf(out,"x"); 59 | fprintf(out, "\n"); 60 | } 61 | } //end printMaze 62 | -------------------------------------------------------------------------------- /P6xMergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MaxSize 20 4 | main() { 5 | void mergeSort(int[], int, int); 6 | int num[] = {4,8,6,16,1,9,14,2,3,5,18,13,17,7,12,11,15,10}; 7 | int n = 18; 8 | mergeSort(num, 0, n-1); 9 | for (int h = 0; h < n; h++) printf("%d ", num[h]); 10 | printf("\n\n"); 11 | } 12 | 13 | void mergeSort(int A[], int lo, int hi) { 14 | void merge(int[], int, int, int); 15 | if (lo < hi) { //list contains at least 2 elements 16 | int mid = (lo + hi) / 2; //get the mid-point subscript 17 | mergeSort(A, lo, mid); //sort first half 18 | mergeSort(A, mid + 1, hi); //sort second half 19 | merge(A, lo, mid, hi); //merge sorted halves 20 | } 21 | } 22 | 23 | void merge(int A[], int lo, int mid, int hi) { 24 | //A[lo..mid] and A[mid+1..hi] are sorted; 25 | //merge the pieces so that A[lo..hi] are sorted 26 | int T[MaxSize]; 27 | int i = lo; 28 | int j = mid + 1; 29 | int k = lo; 30 | while (i <= mid || j <= hi) { 31 | if (i > mid) T[k++] = A[j++]; 32 | else if (j > hi) T[k++] = A[i++]; 33 | else if (A[i] < A[j]) T[k++] = A[i++]; 34 | else T[k++] = A[j++]; 35 | } 36 | for (j = lo; j <= hi; j++) A[j] = T[j]; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /P71GuessingGame.c: -------------------------------------------------------------------------------- 1 | // Program P7.1 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | int answer, guess, random(int, int); 9 | 10 | printf("\nI have thought of a number from 1 to 100.\n"); 11 | printf("Try to guess what it is.\n\n"); 12 | 13 | srand(time (0)); 14 | answer = random(1, 100); 15 | 16 | printf("Your guess? "); 17 | scanf("%d", &guess); 18 | while (guess != answer && guess != 0) { 19 | if (guess < answer) printf("Too low\n"); 20 | else printf("Too high\n"); 21 | printf("Your guess? "); 22 | scanf("%d", &guess); 23 | } 24 | if (guess == 0) printf("Sorry, answer is %d\n", answer); 25 | else printf("Congratulations, you've got it!\n"); 26 | } //end main 27 | 28 | int random(int m, int n) { 29 | //returns a random integer from m to n, inclusive 30 | int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1); 31 | return m + offset; 32 | } //end random 33 | -------------------------------------------------------------------------------- /P72DrillsInAddition.c: -------------------------------------------------------------------------------- 1 | // Program P7.2 2 | 3 | #include 4 | #include 5 | #include 6 | int main() { 7 | int try, maxTries, numProblems, answer, response; 8 | int num1, num2, random(int, int); 9 | 10 | printf("\nWelcome to Problems in Addition\n\n"); 11 | printf("How many problems would you like? "); 12 | scanf("%d", &numProblems); 13 | printf("Maximum tries per problem? "); 14 | scanf("%d", &maxTries); 15 | 16 | srand(time(0)); 17 | 18 | for (int h = 1; h <= numProblems; h++) { 19 | num1 = random(10, 99); 20 | num2 = random(10, 99); 21 | answer = num1 + num2; 22 | for (try = 1; try <= maxTries; try++) { 23 | printf("\nProblem %d, Try %d of %d\n", h, try, maxTries); 24 | printf("%5d + %2d = ", num1, num2); 25 | scanf("%d", &response); 26 | if (response == answer) { 27 | printf("Correct, well done!\n"); 28 | break; 29 | } 30 | if (try < maxTries) printf("Incorrect, try again\n"); 31 | else printf("Sorry, answer is %d\n", answer); 32 | } //end for try 33 | } //end for h 34 | printf("\nThank you for playing. Bye...\n"); 35 | } //end main 36 | 37 | int random(int m, int n) { 38 | //returns a random integer from m to n, inclusive 39 | int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1); 40 | return m + offset; 41 | } //end random 42 | -------------------------------------------------------------------------------- /P73Nim.c: -------------------------------------------------------------------------------- 1 | // Program 7.3 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | int remain, maxPick, userPick, compPick; 9 | int bestPick(int, int), min(int, int); 10 | printf("\nNumber of matches on the table? "); 11 | scanf("%d", &remain); 12 | printf("Maximum pickup per turn? "); 13 | scanf("%d", &maxPick); 14 | printf("\nMatches remaining: %d\n", remain); 15 | 16 | srand(time(0)); 17 | while (1) { //do forever...well, until the game ends 18 | do { 19 | printf("Your turn: "); 20 | scanf("%d", &userPick); 21 | if (userPick > remain) 22 | printf("Cannot pick up more than %d\n", min(remain, maxPick)); 23 | else if (userPick < 1 || userPick > maxPick) 24 | printf("Invalid: must be between 1 and %d\n", maxPick); 25 | } while (userPick > remain || userPick < 1 || userPick > maxPick); 26 | remain = remain - userPick; 27 | printf("Matches remaining: %d\n", remain); 28 | if (remain == 0) { 29 | printf("You lose!!\n"); 30 | exit(0); 31 | } 32 | if (remain == 1) { 33 | printf("You win!!\n"); 34 | exit(0); 35 | } 36 | compPick = bestPick(remain, maxPick); 37 | printf("I pick up %d\n", compPick); 38 | remain = remain - compPick; 39 | printf("Matches remaining: %d\n", remain); 40 | if (remain == 0) { 41 | printf("You win!!\n"); exit(0); 42 | } 43 | if (remain == 1) { 44 | printf("I win!!\n"); exit(0); 45 | } 46 | } //end while(1) 47 | } //end main 48 | 49 | int bestPick(int remain, int maxPick) { 50 | int random(int, int); 51 | if (remain <= maxPick) return remain - 1; //put user in losing position 52 | int r = remain % (maxPick + 1); 53 | if (r == 0) return maxPick; //put user in losing position 54 | if (r == 1) return random(1, maxPick); //computer in losing position 55 | return r - 1; //put user in losing position 56 | } //end bestPick 57 | 58 | int min(int a, int b) { 59 | if (a < b) return a; 60 | return b; 61 | } //end min 62 | 63 | int random(int m, int n) { 64 | //returns a random integer from m to n, inclusive 65 | int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1); 66 | return m + offset; 67 | } //end random 68 | -------------------------------------------------------------------------------- /P74BottleCaps.c: -------------------------------------------------------------------------------- 1 | // Program P7.4 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define MaxSim 20 8 | #define MaxLetters 5 9 | 10 | int main() { 11 | int capsThisSim, totalCaps = 0, doOneSim(); 12 | 13 | srand(time(0)); 14 | printf("\nSimulation Caps collected\n\n"); 15 | for (int sim = 1; sim <= MaxSim; sim++) { 16 | capsThisSim = doOneSim(); 17 | printf("%6d %13d\n", sim, capsThisSim); 18 | totalCaps += capsThisSim; 19 | } 20 | printf("\nAverage caps per simulation: %d\n", totalCaps/MaxSim); 21 | } //end main 22 | 23 | int doOneSim() { 24 | int cap[MaxLetters], numCaps = 0, mango(int []), random(int, int); 25 | for (int h = 0; h < MaxLetters; h++) cap[h] = 0; 26 | while (!mango(cap)) { 27 | int c = random(1, 20); 28 | if (c <= 8) cap[0] = 1; 29 | else if (c <= 13) cap[1] = 1; 30 | else if (c <= 16) cap[2] = 1; 31 | else if (c <= 19) cap[3] = 1; 32 | else cap[4] = 1; 33 | numCaps++; 34 | } 35 | return numCaps; 36 | } //end doOneSim 37 | 38 | int mango(int cap[]) { 39 | for (int h = 0; h < MaxLetters; h++) 40 | if (cap[h] == 0) return 0; 41 | return 1; 42 | } //end mango 43 | 44 | int random(int m, int n) { 45 | //returns a random integer from m to n, inclusive 46 | int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1); 47 | return m + offset; 48 | } //end random 49 | -------------------------------------------------------------------------------- /P75CheckoutSimulation.c: -------------------------------------------------------------------------------- 1 | // Program P7.5 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define MaxCounters 9 8 | 9 | int main() { 10 | int random(int, int), smallest(int[], int, int), max(int, int); 11 | int depart[MaxCounters + 1]; 12 | int m, n, numCust, arriveTime, startServe, serveTime, waitTime; 13 | 14 | printf("\nHow many counters? "); 15 | scanf("%d", &n); 16 | printf("\nHow many customers? "); 17 | scanf("%d", &numCust); 18 | 19 | for (int c = 1; c <= n; c++) depart[c] = 0; 20 | srand(time(0)); 21 | printf("\n Start Service Wait\n"); 22 | printf("Customer Arrives Service Counter Time Departs Time\n\n"); 23 | arriveTime = 0; 24 | for (int c = 1; c <= numCust; c++) { 25 | arriveTime += random(1, 5); 26 | m = smallest(depart, 1, n); 27 | startServe = max(arriveTime, depart[m]); 28 | serveTime = random(3, 10); 29 | depart[m] = startServe + serveTime; 30 | waitTime = startServe - arriveTime; 31 | printf("%5d %8d %7d %6d %7d %8d %5d\n", 32 | c, arriveTime, startServe, m, serveTime, depart[m], waitTime); 33 | } //end for 34 | } //end main 35 | 36 | int smallest(int list[], int lo, int hi) { 37 | //returns the subscript of the smallest value in list 38 | int k = lo; 39 | for (int h = lo + 1; h <= hi; h++) 40 | if (list[h] < list[k]) k = h; 41 | return k; 42 | } //end smallest 43 | 44 | int max(int a, int b) { 45 | if (a > b) return a; 46 | return b; 47 | } //end max 48 | 49 | int random(int m, int n) { 50 | //returns a random integer from m to n, inclusive 51 | int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1); 52 | return m + offset; 53 | } //end random 54 | 55 | -------------------------------------------------------------------------------- /P76EstimatingRoot5.c: -------------------------------------------------------------------------------- 1 | // Program P7.6 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | int maxCount, amountLess; 9 | double r; 10 | 11 | printf("\nHow many numbers to use? "); 12 | scanf("%d", &maxCount); 13 | 14 | srand(time(0)); 15 | amountLess = 0; 16 | for (int h = 1; h <= maxCount; h++) { 17 | r = 2 + rand() / (RAND_MAX + 1.0); 18 | if (r * r < 5) ++amountLess; 19 | } 20 | printf("\nAn approximation to the square root of 5 is %5.3f\n", 21 | 2 + (double) amountLess / maxCount); 22 | } //end main 23 | -------------------------------------------------------------------------------- /P77EstimatingPi.c: -------------------------------------------------------------------------------- 1 | // Program P7.7 2 | 3 | #include 4 | #include 5 | 6 | int main() { 7 | int inS, inC = 0; 8 | double x, y; 9 | 10 | printf("\nHow many numbers to use? "); 11 | scanf("%d", &inS); 12 | 13 | srand(time(0)); 14 | for (int h = 1; h <= inS; h++) { 15 | x = rand() / (RAND_MAX + 1.0); 16 | y = rand() / (RAND_MAX + 1.0); 17 | if (x * x + y * y <= 1) inC++; 18 | } 19 | printf("\nAn approximation to pi is %5.3f\n", 4.0 * inC / inS); 20 | } 21 | -------------------------------------------------------------------------------- /P81Average.c: -------------------------------------------------------------------------------- 1 | // Program P8.1 2 | 3 | //read numbers from a file and find their average; 0 ends the data 4 | #include 5 | int main() { 6 | FILE * in = fopen("input.txt", "r"); 7 | int num, sum = 0, n = 0; 8 | fscanf(in, "%d", &num); 9 | while (num != 0) { 10 | n = n + 1; 11 | sum = sum + num; 12 | fscanf(in, "%d", &num); 13 | } 14 | if (n == 0) printf("\nNo numbers entered\n"); 15 | else { 16 | printf("\n%d numbers were entered\n", n); 17 | printf("The sum is %d\n", sum); 18 | printf("The average is %3.2f\n", (double) sum/n); 19 | } 20 | fclose(in); 21 | } //end main 22 | -------------------------------------------------------------------------------- /P82CompareFiles.c: -------------------------------------------------------------------------------- 1 | // Program P8.2 2 | 3 | #include 4 | #include 5 | #define MaxName 20 6 | #define MaxLine 101 7 | int main() { 8 | char name1[MaxName], name2[MaxName]; 9 | char line1[MaxLine], line2[MaxLine]; 10 | FILE *file1, *file2, *getFileName(char *, char *); 11 | char *eof1, *eof2; 12 | 13 | int lineNum = 0; 14 | file1 = getFileName("First file?", name1); 15 | file2 = getFileName("Second file?", name2); 16 | 17 | while (((eof1 = fgets(line1, MaxLine, file1)) != NULL) && 18 | ((eof2 = fgets(line2, MaxLine, file2)) != NULL) && 19 | (strcmp (line1, line2) == 0)) 20 | lineNum++; 21 | // at this stage, linenum is the number of matching lines found 22 | if (eof1 == NULL) //first file ended 23 | if (fgets(line2, MaxLine, file2) == NULL) //second also ended 24 | printf("\nFiles are identical\n\n"); 25 | else //first file ended, second file not ended 26 | printf("\n%s, with %d line(s), is a subset of %s\n", 27 | name1, lineNum, name2); 28 | else if (eof2 == NULL) //first file not ended, second file ended 29 | printf("\n%s, with %d line(s), is a subset of %s\n", 30 | name2, lineNum, name1); 31 | else { // mismatch found 32 | printf("\nThe files differ at line %d\n", ++lineNum); 33 | printf("The lines are \n%s and \n%s", line1, line2); 34 | } 35 | fclose(file1); 36 | fclose(file2); 37 | } //end main 38 | 39 | FILE * getFileName(char *prompt, char *name) { 40 | //store the filename in 'name' and return the pointer to the file 41 | FILE *filePtr; 42 | do { 43 | printf("%s ", prompt); gets(name); 44 | if ((filePtr = fopen(name, "r")) == NULL) 45 | printf("File does not exist or access denied\n"); 46 | } while (filePtr == NULL); 47 | return filePtr; 48 | } //end getFileName 49 | -------------------------------------------------------------------------------- /P83ReadTextStoreBinary.c: -------------------------------------------------------------------------------- 1 | //Program P8.3 2 | 3 | #include 4 | int main() { 5 | FILE *intFile; 6 | int num; 7 | 8 | if ((intFile = fopen("num.bin", "wb")) == NULL) { 9 | printf("Cannot open file\n"); 10 | return -1; 11 | } 12 | while (scanf("%d", &num) == 1) 13 | fwrite(&num, sizeof(int), 1, intFile); 14 | fclose (intFile); 15 | } //end main 16 | -------------------------------------------------------------------------------- /P84ReadBinaryWriteText.c: -------------------------------------------------------------------------------- 1 | //Program P8.4 2 | 3 | #include 4 | int main() { 5 | FILE *intFile; 6 | int num; 7 | 8 | if ((intFile = fopen("num.bin", "rb")) == NULL) { 9 | printf("Cannot open file\n"); 10 | return -1; 11 | } 12 | 13 | while (fread(&num, sizeof(int), 1, intFile) == 1) 14 | printf("%d\n", num); 15 | 16 | if (feof(intFile)) printf("\nEnd of list\n"); 17 | else printf("\nError reading file\n"); 18 | 19 | fclose(intFile); 20 | } //end main 21 | -------------------------------------------------------------------------------- /P85BinFileOfStructures.c: -------------------------------------------------------------------------------- 1 | //Program P8.5 2 | 3 | 4 | #include 5 | 6 | typedef struct partRecord { 7 | char partNum[7]; 8 | char name[25]; 9 | int amtInStock; 10 | double unitPrice; 11 | } PartRecord; 12 | 13 | int main() { 14 | FILE *ftxt, *fbin; 15 | PartRecord part; 16 | 17 | if ((ftxt = fopen("parts.txt", "r")) == NULL) { 18 | printf("Cannot open parts file\n"); 19 | return -1; 20 | } 21 | 22 | if ((fbin = fopen("parts.bin", "wb")) == NULL) { 23 | printf("Cannot create file\n"); 24 | return -1; 25 | } 26 | 27 | while (fscanf(ftxt, "%s %s %d %lf", part.partNum, part.name, 28 | &part.amtInStock, &part.unitPrice) == 4) 29 | if (fwrite(&part, sizeof(PartRecord), 1, fbin) != 1) { 30 | printf("Error in writing file\n"); 31 | return -1; 32 | } 33 | 34 | fclose(ftxt); 35 | fclose(fbin); 36 | } //end main 37 | -------------------------------------------------------------------------------- /P86FetchBinaryRecords.c: -------------------------------------------------------------------------------- 1 | // Program P8.6 2 | 3 | #include 4 | 5 | typedef struct partRecord { 6 | char partNum[7]; 7 | char name[25]; 8 | int amtInStock; 9 | double unitPrice; 10 | } PartRecord; 11 | 12 | int main() { 13 | FILE *fbin; 14 | PartRecord part; 15 | int n; 16 | 17 | if ((fbin = fopen("parts.bin", "rb")) == NULL) { 18 | printf("Cannot open file\n"); 19 | return -1; 20 | } 21 | printf("Enter record number: "); 22 | scanf("%d", &n); 23 | while (n != 0) { 24 | fseek(fbin, (n - 1) * sizeof(PartRecord), SEEK_SET); 25 | fread(&part, sizeof(PartRecord), 1, fbin); 26 | 27 | printf("\nPart number: %s\n", part.partNum); 28 | printf("Part name: %s\n", part.name); 29 | printf("Amount in stock: %d\n", part.amtInStock); 30 | printf("Price: $%3.2f\n\n", part.unitPrice); 31 | 32 | printf("Enter record number: "); 33 | scanf("%d", &n); 34 | } 35 | fclose(fbin); 36 | } //end main 37 | -------------------------------------------------------------------------------- /P87CreateIndexedFile.c: -------------------------------------------------------------------------------- 1 | // Program P8.7 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define PartNumSize 6 8 | #define MaxName 24 9 | #define MaxRecords 100 10 | 11 | typedef struct partRecord { 12 | char partNum[PartNumSize + 1]; 13 | char name[MaxName + 1]; 14 | int amtInStock; 15 | double unitPrice; 16 | } PartRecord; 17 | typedef struct indexEntry { 18 | char partNum[PartNumSize + 1]; 19 | int recNum; 20 | } IndexEntry; 21 | 22 | int main() { 23 | IndexEntry index[MaxRecords + 1]; 24 | void createMaster(char *, IndexEntry[], int); 25 | void saveIndex(char *, IndexEntry[], int); 26 | createMaster("parts.bin", index, MaxRecords); 27 | saveIndex("index.bin", index, MaxRecords + 1); 28 | } //end main 29 | 30 | void createMaster(char *fileName, IndexEntry index[], int maxRecords) { 31 | // stores records in 'fileName'; caters for maxRecords index entries; 32 | // sets index[0].recNum to the number of index entries actually used 33 | FILE *ftxt, *fbin; 34 | PartRecord part; 35 | int searchResult, search(char[], IndexEntry[], int); 36 | int numRecords = 0; 37 | 38 | if ((ftxt = fopen("parts.txt", "r")) == NULL) { 39 | printf("Cannot open parts file\n"); return; 40 | } 41 | 42 | if ((fbin = fopen("parts.bin", "wb")) == NULL) { 43 | printf("Cannot create file\n"); 44 | return; 45 | } 46 | 47 | while (fscanf(ftxt, "%s %s %d %lf", part.partNum, part.name, 48 | &part.amtInStock, &part.unitPrice) == 4) { 49 | searchResult = search(part.partNum, index, numRecords); 50 | if (searchResult > 0) 51 | printf("Duplicate part: %s ignored\n", part.partNum); 52 | else { //this is a new part number 53 | if (numRecords == maxRecords) { 54 | printf("Too many records: only %d allowed\n", maxRecords); 55 | exit(1); 56 | } 57 | //the index has room; shift entries to accommodate new part 58 | int j; 59 | for (j = numRecords; j >= -searchResult; j--) 60 | index[j + 1] = index[j]; 61 | strcpy(index[-searchResult].partNum, part.partNum); 62 | index[-searchResult].recNum = ++numRecords; 63 | if (fwrite(&part, sizeof(PartRecord), 1, fbin) != 1) { 64 | printf("Error in writing file\n"); exit(1); 65 | } 66 | printf("%s %-11s %2d %5.2f\n", part.partNum, part.name, 67 | part.amtInStock, part.unitPrice); 68 | } 69 | } 70 | index[0].recNum = numRecords; 71 | fclose(fbin); 72 | } //end createMaster 73 | 74 | int search(char key[], IndexEntry list[], int n) { 75 | //searches list[1..n] for key. If found, it returns the location; otherwise 76 | //it returns the negative of the location in which key should be inserted. 77 | int lo = 1; int hi = n; 78 | while (lo <= hi) { // as long as more elements remain to consider 79 | int mid = (lo + hi) / 2; 80 | int cmp = strcmp(key, list[mid].partNum); 81 | if (cmp == 0) return mid; // search succeeds 82 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 83 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 84 | } 85 | return -lo; // key not found; insert in location lo 86 | } //end search 87 | 88 | void saveIndex(char *fileName, IndexEntry index[], int max) { 89 | //save the index in fileName; max is the size of index. 90 | FILE *indexFile; 91 | if ((indexFile = fopen(fileName, "wb")) == NULL) { 92 | printf("Cannot create file %s. Index not saved\n", fileName); 93 | exit(1); 94 | } 95 | 96 | fwrite(&max, sizeof(int), 1, indexFile); //save the index size first 97 | fwrite(index, sizeof(IndexEntry), max, indexFile); //save the index 98 | fclose(indexFile); 99 | } //end saveIndex 100 | -------------------------------------------------------------------------------- /P88RetrieveIndexedFile.c: -------------------------------------------------------------------------------- 1 | // Program P8.8 2 | 3 | #include 4 | #include 5 | #include 6 | #define PartNumSize 6 7 | #define MaxName 24 8 | #define MaxRecords 100 9 | typedef struct partRecord { 10 | char partNum[PartNumSize + 1]; 11 | char name[MaxName + 1]; 12 | int amtInStock; double unitPrice; 13 | } PartRecord; 14 | typedef struct indexEntry { 15 | char partNum[PartNumSize + 1]; 16 | int recNum; 17 | } IndexEntry; 18 | 19 | int main() { 20 | FILE *partFile; 21 | IndexEntry index[MaxRecords + 1]; 22 | void retrieveIndex(char *, IndexEntry[]); 23 | void retrieveRecords(IndexEntry[], FILE *); 24 | 25 | if ((partFile = fopen("parts.bin", "rb")) == NULL) { 26 | printf("Cannot open file\n"); return -1; 27 | } 28 | retrieveIndex("index.bin", index); 29 | retrieveRecords(index, partFile); 30 | fclose(partFile); 31 | } //end main 32 | 33 | void retrieveRecords(IndexEntry index[], FILE *pf) { 34 | char pnum[PartNumSize * 2]; //to cater for extra characters typed 35 | PartRecord part; 36 | int search(char[], IndexEntry[], int); 37 | 38 | int numRecords = index[0].recNum; 39 | printf("\nEnter a part number (E to end): "); 40 | scanf("%s", pnum); 41 | while (strcmp(pnum, "E") != 0) { 42 | int n = search(pnum, index, numRecords); 43 | if (n < 0) printf("Part not found\n"); 44 | else { 45 | fseek(pf, (index[n].recNum - 1)*sizeof(PartRecord), SEEK_SET); 46 | fread(&part, sizeof(PartRecord), 1, pf); 47 | printf("\nPart number: %s\n", part.partNum); 48 | printf("Part name: %s\n", part.name); 49 | printf("Amount in stock: %d\n", part.amtInStock); 50 | printf("Price: $%3.2f\n", part.unitPrice); 51 | } 52 | printf("\nEnter a part number (E to end): "); 53 | scanf("%s", pnum); 54 | } //end while 55 | } //end retrieveRecords 56 | 57 | void retrieveIndex(char *fileName, IndexEntry index[]) { 58 | FILE *indexFile; 59 | int maxRecords; 60 | 61 | if ((indexFile = fopen(fileName, "rb")) == NULL){ 62 | printf("cannot open index file.\n"); 63 | exit(1); 64 | } 65 | fread(&maxRecords, sizeof(int), 1,indexFile); 66 | fread(index, sizeof(IndexEntry), maxRecords, indexFile); 67 | fclose(indexFile); 68 | } //end retrieveIndex 69 | 70 | int search(char key[], IndexEntry list[], int n) { 71 | //searches list[1..n] for key. If found, it returns the location; otherwise 72 | //it returns the negative of the location in which key should be inserted. 73 | int lo = 1; int hi = n; 74 | while (lo <= hi) { // as long as more elements remain to consider 75 | int mid = (lo + hi) / 2; 76 | int cmp = strcmp(key, list[mid].partNum); 77 | if (cmp == 0) return mid; // search succeeds 78 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 79 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 80 | } 81 | return -lo; // key not found; insert in location lo 82 | } //end search 83 | -------------------------------------------------------------------------------- /P89UpdateRandomAccessFile.c: -------------------------------------------------------------------------------- 1 | // Program P8.9 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define PartNumSize 6 8 | #define MaxName 24 9 | #define MaxRecords 100 10 | 11 | typedef struct partRecord { 12 | char partNum[PartNumSize + 1]; 13 | char name[MaxName + 1]; 14 | int amtInStock; 15 | double unitPrice; 16 | } PartRecord; 17 | 18 | typedef struct indexEntry { 19 | char partNum[PartNumSize + 1]; 20 | int recNum; 21 | } IndexEntry; 22 | 23 | int main() { 24 | FILE *partFile; 25 | IndexEntry index[MaxRecords + 1]; 26 | void retrieveIndex(char *, IndexEntry[]); 27 | void updateRecord(int, FILE *); 28 | int search(char[], IndexEntry[], int); 29 | char pnum[PartNumSize + 1]; 30 | 31 | if ((partFile = fopen("parts.bin", "rb+")) == NULL) { 32 | printf("Cannot open file\n"); 33 | return -1; 34 | } 35 | retrieveIndex("index.bin", index); 36 | int numRecords = index[0].recNum; 37 | 38 | printf("\nEnter a part number (E to end): "); 39 | scanf("%s", pnum); 40 | while (strcmp(pnum, "E") != 0) { 41 | int n = search(pnum, index, numRecords); 42 | if (n < 0) printf("Part not found\n"); 43 | else updateRecord(index[n].recNum, partFile); 44 | printf("\nEnter a part number (E to end): "); 45 | scanf("%s", pnum); 46 | } // end while 47 | fclose(partFile); 48 | } //end main 49 | 50 | void updateRecord(int n, FILE *pf) { 51 | //update record n in file pf 52 | PartRecord part; 53 | int amtSold; 54 | 55 | fseek(pf, (n - 1) * sizeof(PartRecord), SEEK_SET); 56 | fread(&part, sizeof(PartRecord), 1, pf); 57 | printf("Enter amount sold: "); 58 | scanf("%d", &amtSold); 59 | if (amtSold > part.amtInStock) 60 | printf("You have %d: cannot sell more, ignored\n", part.amtInStock); 61 | else { 62 | part.amtInStock -= amtSold; 63 | printf("Amount remaining: %d\n", part.amtInStock); 64 | fseek(pf, (n - 1) * sizeof(PartRecord), SEEK_SET); 65 | fwrite(&part, sizeof(PartRecord), 1, pf); 66 | printf("%s %-11s %2d %5.2f\n", part.partNum, part.name, part.amtInStock, part.unitPrice); 67 | } //end if 68 | } //end updateRecord 69 | 70 | void retrieveIndex(char *fileName, IndexEntry index[]) { 71 | FILE *indexFile; 72 | int maxRecords; 73 | 74 | if ((indexFile = fopen(fileName, "rb")) == NULL){ 75 | printf("cannot open index file.\n"); 76 | exit(1); 77 | } 78 | fread(&maxRecords, sizeof(int), 1,indexFile); 79 | fread(index, sizeof(IndexEntry), maxRecords, indexFile); 80 | fclose(indexFile); 81 | } //end retrieveIndex 82 | 83 | int search(char key[], IndexEntry list[], int n) { 84 | //searches list[1..n] for key. If found, it returns the location; otherwise 85 | //it returns the negative of the location in which key should be inserted. 86 | int lo = 1; int hi = n; 87 | while (lo <= hi) { // as long as more elements remain to consider 88 | int mid = (lo + hi) / 2; 89 | int cmp = strcmp(key, list[mid].partNum); 90 | if (cmp == 0) return mid; // search succeeds 91 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 92 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 93 | } 94 | return -lo; // key not found; insert in location lo 95 | } //end search 96 | -------------------------------------------------------------------------------- /P91BuildTraverseBinaryTree.c: -------------------------------------------------------------------------------- 1 | // Program P9.1 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define MaxWordSize 20 8 | 9 | typedef struct { 10 | char word[MaxWordSize+1]; 11 | } NodeData; 12 | 13 | typedef struct treeNode { 14 | NodeData data; 15 | struct treeNode *left, *right; 16 | } TreeNode, *TreeNodePtr; 17 | 18 | typedef struct { 19 | TreeNodePtr root; 20 | } BinaryTree; 21 | 22 | int main() { 23 | TreeNodePtr buildTree(FILE *); 24 | void preOrder(TreeNodePtr); 25 | void inOrder(TreeNodePtr); 26 | void postOrder(TreeNodePtr); 27 | 28 | FILE * in = fopen("btree.in", "r"); 29 | BinaryTree bt; 30 | bt.root = buildTree(in); 31 | printf("\nThe pre-order traversal is: "); 32 | preOrder(bt.root); 33 | printf("\n\nThe in-order traversal is: "); 34 | inOrder(bt.root); 35 | printf("\n\nThe post-order traversal is: "); 36 | postOrder(bt.root); 37 | printf("\n\n"); 38 | fclose(in); 39 | } // end main 40 | 41 | TreeNodePtr buildTree(FILE * in) { 42 | char str[MaxWordSize+1]; 43 | fscanf(in, "%s", str); 44 | if (strcmp(str, "@") == 0) return NULL; 45 | TreeNodePtr p = (TreeNodePtr) malloc(sizeof(TreeNode)); 46 | strcpy(p -> data.word, str); 47 | p -> left = buildTree(in); 48 | p -> right = buildTree(in); 49 | return p; 50 | } //end buildTree 51 | 52 | void visit(TreeNodePtr node) { 53 | printf("%s ", node -> data.word); 54 | } //end visit 55 | void preOrder(TreeNodePtr node) { 56 | void visit(TreeNodePtr); 57 | if (node != NULL) { 58 | visit(node); 59 | preOrder(node -> left); 60 | preOrder(node -> right); 61 | } 62 | } //end preOrder 63 | 64 | void inOrder(TreeNodePtr node) { 65 | void visit(TreeNodePtr); 66 | if (node != NULL) { 67 | inOrder(node -> left); 68 | visit(node); 69 | inOrder(node -> right); 70 | } 71 | } //end inOrder 72 | 73 | void postOrder(TreeNodePtr node) { 74 | void visit(TreeNodePtr); 75 | if (node != NULL) { 76 | postOrder(node -> left); 77 | postOrder(node -> right); 78 | visit(node); 79 | } 80 | } //end postOrder 81 | -------------------------------------------------------------------------------- /P92WordFrequency.c: -------------------------------------------------------------------------------- 1 | // Program P9.2 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #define MaxWordSize 20 8 | 9 | typedef struct { 10 | char word[MaxWordSize+1]; 11 | int freq; 12 | } NodeData; 13 | 14 | typedef struct treeNode { 15 | NodeData data; 16 | struct treeNode *left, *right; 17 | } TreeNode, *TreeNodePtr; 18 | 19 | typedef struct { 20 | TreeNodePtr root; 21 | } BinaryTree; 22 | 23 | int main() { 24 | int getWord(FILE *, char[]); 25 | TreeNodePtr newTreeNode(NodeData); 26 | NodeData newNodeData(char[], int); 27 | TreeNodePtr findOrInsert(BinaryTree, NodeData); 28 | void inOrder(FILE *, TreeNodePtr); 29 | 30 | char word[MaxWordSize+1]; 31 | 32 | FILE * in = fopen("wordFreq.in", "r"); 33 | FILE * out = fopen("wordFreq.out", "w"); 34 | 35 | BinaryTree bst; 36 | bst.root = NULL; 37 | 38 | while (getWord(in, word) != 0) { 39 | if (bst.root == NULL) 40 | bst.root = newTreeNode(newNodeData(word, 1)); 41 | else { 42 | TreeNodePtr node = findOrInsert(bst, newNodeData(word, 0)); 43 | node -> data.freq++; 44 | } 45 | } 46 | 47 | fprintf(out, "\nWords Frequency\n\n"); 48 | inOrder(out, bst.root); fprintf(out, "\n\n"); 49 | fclose(in); 50 | fclose(out); 51 | } // end main 52 | 53 | int getWord(FILE * in, char str[]) { 54 | // stores the next word, if any, in str; word is converted to lowercase 55 | // returns 1 if a word is found; 0, otherwise 56 | char ch; 57 | int n = 0; 58 | // read over non-letters 59 | while (!isalpha(ch = getc(in)) && ch != EOF) ; //empty while body 60 | if (ch == EOF) return 0; 61 | str[n++] = tolower(ch); 62 | while (isalpha(ch = getc(in)) && ch != EOF) 63 | if (n < MaxWordSize) str[n++] = tolower(ch); 64 | str[n] = '\0'; 65 | return 1; 66 | } // end getWord 67 | 68 | TreeNodePtr findOrInsert(BinaryTree bt, NodeData d) { 69 | //searches for d; if found, return pointer to node containing d 70 | //else insert a node containing d and return pointer to new node 71 | TreeNodePtr newTreeNode(NodeData); 72 | 73 | if (bt.root == NULL) return newTreeNode(d); 74 | TreeNodePtr curr = bt.root; 75 | int cmp; 76 | while ((cmp = strcmp(d.word, curr -> data.word)) != 0) { 77 | if (cmp < 0) { //try left 78 | if (curr -> left == NULL) return curr -> left = newTreeNode(d); 79 | curr = curr -> left; 80 | } 81 | else { //try right 82 | if (curr -> right == NULL) return curr -> right = newTreeNode(d); 83 | curr = curr -> right; 84 | } 85 | } 86 | //d is in the tree; return pointer to the node 87 | return curr; 88 | } //end findOrInsert 89 | 90 | TreeNodePtr newTreeNode(NodeData d) { 91 | TreeNodePtr p = (TreeNodePtr) malloc(sizeof(TreeNode)); 92 | p -> data = d; 93 | p -> left = p -> right = NULL; 94 | return p; 95 | } //end newTreeNode 96 | 97 | void inOrder(FILE * out, TreeNodePtr node) { 98 | if (node!= NULL) { 99 | inOrder(out, node -> left); 100 | fprintf(out, "%-15s %2d\n", node -> data.word, node -> data.freq); 101 | inOrder(out, node -> right); 102 | } 103 | } //end inOrder 104 | 105 | NodeData newNodeData(char str[], int n) { 106 | NodeData temp; 107 | strcpy(temp.word, str); 108 | temp.freq = n; 109 | return temp; 110 | } //end newNodeData 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Advanced Topics in C*](http://www.apress.com/9781430264002) by Noel Kalicharan (Apress, 2013). 4 | 5 | ![Cover image](9781430264002.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /btree.in: -------------------------------------------------------------------------------- 1 | C E F @ H @ @ B @ @ G A @ @ N J @ @ K @ @ 2 | -------------------------------------------------------------------------------- /cell.in: -------------------------------------------------------------------------------- 1 | 5 7 2 | 0 1 0 1 1 1 0 3 | 0 0 1 1 0 0 0 4 | 1 1 0 1 0 0 1 5 | 1 0 1 0 0 1 1 6 | 1 1 0 0 0 1 0 7 | -------------------------------------------------------------------------------- /cell.out: -------------------------------------------------------------------------------- 1 | 2 | Number of organisms = 5 3 | 4 | Position of organisms are shown here 5 | 6 | 0 1 0 2 2 2 0 7 | 0 0 2 2 0 0 0 8 | 3 3 0 2 0 0 4 9 | 3 0 5 0 0 4 4 10 | 3 3 0 0 0 4 0 11 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /file1.txt: -------------------------------------------------------------------------------- 1 | one and one are two 2 | two and two are four 3 | three and three are six 4 | four and four are eight 5 | five and five are ten 6 | six and six are twelve 7 | -------------------------------------------------------------------------------- /file2.txt: -------------------------------------------------------------------------------- 1 | one and one are two 2 | two and two are four 3 | three and three are six 4 | four and four are eight 5 | this is the fifth line 6 | six and six are twelve 7 | -------------------------------------------------------------------------------- /heap.in: -------------------------------------------------------------------------------- 1 | 37 25 43 65 48 84 73 18 79 56 69 32 2 | -------------------------------------------------------------------------------- /index.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/index.bin -------------------------------------------------------------------------------- /input.txt: -------------------------------------------------------------------------------- 1 | "Jones, John" 24 M 2 | "Mohammed, Lisa" 33 F 3 | "Singh, Sandy" 29 F 4 | "Layne, Dennis" 49 M 5 | "Singh, Cindy" 16 F 6 | "Ali, Imran" 39 M 7 | "Kelly, Trudy" 30 F 8 | "Cox, Kerry" 25 M 9 | "END" 10 | "Kelly, Trudy" 11 | "Layne, Dennis" 12 | "Layne, Cindy" 13 | "END" 14 | -------------------------------------------------------------------------------- /maze.in: -------------------------------------------------------------------------------- 1 | 8 10 6 6 2 | 1 1 1 1 1 1 1 1 1 1 3 | 1 0 1 0 0 0 1 0 0 1 4 | 1 0 1 0 1 0 1 1 0 1 5 | 1 0 0 0 1 0 0 0 0 1 6 | 1 0 1 1 1 1 1 1 0 1 7 | 1 0 1 0 1 0 1 1 0 0 8 | 1 0 0 0 0 0 1 1 0 1 9 | 1 1 1 1 1 1 1 1 1 1 10 | -------------------------------------------------------------------------------- /maze.out: -------------------------------------------------------------------------------- 1 | ########## 2 | # #xxx# # 3 | # #x#x## # 4 | #xxx#xxxx# 5 | #x######x# 6 | #x# #S##xx 7 | #xxxxx## # 8 | ########## 9 | -------------------------------------------------------------------------------- /num.bin: -------------------------------------------------------------------------------- 1 | ".9@ -------------------------------------------------------------------------------- /numbers.in: -------------------------------------------------------------------------------- 1 | 24 57 35 37 31 98 85 47 60 32 48 82 16 96 87 46 53 92 71 56 2 | 73 85 47 46 22 40 95 32 54 67 31 44 74 40 58 42 88 29 78 87 3 | 45 13 73 29 84 48 85 29 66 73 87 17 10 83 95 25 44 93 32 39 4 | -------------------------------------------------------------------------------- /output.txt: -------------------------------------------------------------------------------- 1 | 'jumped' not added to table 2 | 'then' not added to table 3 | 'why' not added to table 4 | 'did' not added to table 5 | 'jump' not added to table 6 | 'to' not added to table 7 | 'recuperate' not added to table 8 | 9 | Words Frequency 10 | 11 | brown 3 12 | congratula 1 13 | dog 3 14 | fox 3 15 | if 1 16 | jumps 1 17 | lazy 3 18 | over 3 19 | quick 3 20 | the 6 21 | -------------------------------------------------------------------------------- /p46Countout.c: -------------------------------------------------------------------------------- 1 | // Program P4.6 2 | 3 | #include 4 | #include 5 | 6 | typedef struct node { 7 | int num; 8 | struct node *next; 9 | } Node, *NodePtr; 10 | 11 | int main() { 12 | NodePtr curr, linkCircular(int), playGame(NodePtr, int, int); 13 | int n, m; 14 | 15 | do { 16 | printf("Enter number of children and length of count-out: "); 17 | scanf("%d %d", &n, &m); 18 | } while (n < 1 || m < 1); 19 | 20 | curr = linkCircular(n); //link children in a circular list 21 | curr = playGame(curr, n-1, m); //eliminate n-1 children 22 | printf("The winning child: %d\n", curr -> num); 23 | } //end main 24 | 25 | NodePtr makeNode(int n) { 26 | NodePtr np = (NodePtr) malloc(sizeof (Node)); 27 | np -> num = n; 28 | np -> next = NULL; 29 | return np; 30 | } //end makeNode 31 | 32 | NodePtr linkCircular(int n) { 33 | //link n children in a circular list; return pointer to first child 34 | NodePtr first, np, makeNode(int); 35 | 36 | first = np = makeNode(1); //first child 37 | for (int h = 2; h <= n; h++) { //link the others 38 | np -> next = makeNode(h); 39 | np = np -> next; 40 | } 41 | np -> next = first; //set last child to point to first 42 | return first; 43 | } //end linkCircular 44 | 45 | NodePtr playGame(NodePtr first, int x, int m) { 46 | NodePtr prev, curr = first; 47 | //eliminate x children 48 | for (int h = 1; h <= x; h++) { 49 | //curr is pointing at the first child to be counted; 50 | //count m-1 more to get to the mth child 51 | for (int c = 1; c < m; c++) { 52 | prev = curr; 53 | curr = curr -> next; 54 | } 55 | //delete the mth child 56 | prev -> next = curr -> next; 57 | free(curr); 58 | curr = prev -> next; //set curr to the child after the one eliminated 59 | } 60 | return curr; 61 | } //end playGame 62 | -------------------------------------------------------------------------------- /parts.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-c/073799765b18ba4ecd543260a46ffe047f1ca38b/parts.bin -------------------------------------------------------------------------------- /parts.txt: -------------------------------------------------------------------------------- 1 | PKL070 Park-Lens 8 6.50 2 | BLJ375 Ball-Joint 12 11.95 3 | PKL070 Park-Lens 8 6.50 4 | FLT015 Oil-Filter 23 7.95 5 | DKP080 Disc-Pads 16 9.99 6 | GSF555 Gas-Filter 9 4.50 7 | FLT015 Oil-Filter 23 7.95 8 | -------------------------------------------------------------------------------- /passage.txt: -------------------------------------------------------------------------------- 1 | The quick brown fox jumps over the lazy dog. Congratulations! 2 | If the quick brown fox jumped over the lazy dog then 3 | Why did the quick brown fox jump over the lazy dog? 4 | To recuperate! 5 | -------------------------------------------------------------------------------- /queue0.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct { 4 | int head, tail; 5 | int QA[MaxQ]; 6 | } QType, *Queue; 7 | 8 | Queue initQueue() { 9 | Queue qp = (Queue) malloc(sizeof(QType)); 10 | qp -> head = qp -> tail = 0; 11 | return qp; 12 | } 13 | 14 | int empty(Queue Q) { 15 | return (Q -> head == Q -> tail); 16 | } 17 | 18 | void enqueue(Queue Q, int n) { 19 | if (Q -> tail == MaxQ - 1) Q -> tail = 0; 20 | else ++(Q -> tail); 21 | if (Q -> tail == Q -> head) { 22 | printf("\nQueue is full\n"); 23 | exit(1); 24 | } 25 | Q -> QA[Q -> tail] = n; 26 | } 27 | 28 | int dequeue(Queue Q) { 29 | if (empty(Q)) { 30 | printf("\nAttempt to remove from an empty queue\n"); 31 | exit(1); 32 | } 33 | if (Q -> head == MaxQ - 1) Q -> head = 0; 34 | else ++(Q -> head); 35 | return Q -> QA[Q -> head]; 36 | } 37 | -------------------------------------------------------------------------------- /queue1.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct node { 4 | QueueData data; 5 | struct node *next; 6 | } Node, *NodePtr; 7 | 8 | typedef struct queueType { 9 | NodePtr head, tail; 10 | } QueueType, *Queue; 11 | 12 | Queue initQueue() { 13 | Queue qp = (Queue) malloc(sizeof(QueueType)); 14 | qp -> head = NULL; 15 | qp -> tail = NULL; 16 | return qp; 17 | } //end initQueue 18 | 19 | int empty(Queue Q) { 20 | return (Q -> head == NULL); 21 | } //end empty 22 | 23 | void enqueue(Queue Q, QueueData d) { 24 | NodePtr np = (NodePtr) malloc(sizeof(Node)); 25 | np -> data = d; 26 | np -> next = NULL; 27 | if (empty(Q)) { 28 | Q -> head = np; 29 | Q -> tail = np; 30 | } 31 | else { 32 | Q -> tail -> next = np; 33 | Q -> tail = np; 34 | } 35 | } //end enqueue 36 | 37 | QueueData dequeue(Queue Q) { 38 | if (empty(Q)) { 39 | printf("\nAttempt to remove from an empty queue\n"); 40 | exit(1); 41 | } 42 | QueueData hold = Q -> head -> data; 43 | NodePtr temp = Q -> head; 44 | Q -> head = Q -> head -> next; 45 | if (Q -> head == NULL) Q -> tail = NULL; 46 | free(temp); 47 | return hold; 48 | } //end dequeue 49 | -------------------------------------------------------------------------------- /results.txt: -------------------------------------------------------------------------------- 1 | Invalid vote: 8 2 | Invalid vote: 9 3 | 4 | Number of voters: 30 5 | Number of valid votes: 28 6 | Number of spoilt votes: 2 7 | 8 | Candidate Score 9 | 10 | Anisa Sawh 6 11 | Carol Khan 2 12 | Denise Duncan 3 13 | Gary Owen 3 14 | Kamal Ramdhan 6 15 | Michael Ali 4 16 | Victor Taylor 4 17 | 18 | The winner(s) 19 | Anisa Sawh 20 | Kamal Ramdhan 21 | -------------------------------------------------------------------------------- /shell.in: -------------------------------------------------------------------------------- 1 | 67 90 28 84 29 58 25 32 2 | 16 64 13 71 82 10 51 57 3 | -------------------------------------------------------------------------------- /stack.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct node { 4 | StackData data; 5 | struct node *next; 6 | } Node, *NodePtr; 7 | 8 | typedef struct stackType { 9 | NodePtr top; 10 | } StackType, *Stack; 11 | 12 | Stack initStack() { 13 | Stack sp = (Stack) malloc(sizeof(StackType)); 14 | sp -> top = NULL; 15 | return sp; 16 | } 17 | 18 | int empty(Stack S) { 19 | return (S -> top == NULL); 20 | } 21 | 22 | void push(Stack S, StackData d) { 23 | NodePtr np = (NodePtr) malloc(sizeof(Node)); 24 | np -> data = d; 25 | np -> next = S -> top; 26 | S -> top = np; 27 | } 28 | 29 | StackData pop(Stack S) { 30 | if (empty(S)) { 31 | printf("\nAttempt to pop an empty stack\n"); 32 | exit(1); 33 | } 34 | StackData hold = S -> top -> data; 35 | NodePtr temp = S -> top; 36 | S -> top = S -> top -> next; 37 | free(temp); 38 | return hold; 39 | } 40 | 41 | StackData peek(Stack S) { 42 | if (!empty(S)) return S -> top -> data; 43 | printf("\nAttempt to peek at an empty stack\n"); 44 | exit(1); 45 | } 46 | -------------------------------------------------------------------------------- /stack0.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define RogueValue -9999 3 | 4 | typedef struct node { 5 | int num; 6 | struct node *next; 7 | } Node, *NodePtr; 8 | 9 | typedef struct stackType { 10 | NodePtr top; 11 | } StackType, *Stack; 12 | 13 | Stack initStack() { 14 | Stack sp = (Stack) malloc(sizeof(StackType)); 15 | sp -> top = NULL; 16 | return sp; 17 | } 18 | 19 | int empty(Stack S) { 20 | return (S -> top == NULL); 21 | } //end empty 22 | 23 | void push(Stack S, int n) { 24 | NodePtr np = (NodePtr) malloc(sizeof(Node)); 25 | np -> num = n; 26 | np -> next = S -> top; 27 | S -> top = np; 28 | } //end push 29 | 30 | int pop(Stack S) { 31 | if (empty(S)) return RogueValue; 32 | int hold = S -> top -> num; 33 | NodePtr temp = S -> top; 34 | S -> top = S -> top -> next; 35 | free(temp); 36 | return hold; 37 | } //end pop 38 | -------------------------------------------------------------------------------- /structSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct { 4 | char name[31]; 5 | int age; 6 | char gender; 7 | } Student; 8 | 9 | void sort(Student list[], int n) { 10 | //sort list[0] to list[n-1] by name using an insertion sort 11 | Student temp; 12 | int k; 13 | for (int h = 1; h < n; h++) { 14 | Student temp = list[h]; 15 | k = h - 1; 16 | while (k >= 0 && strcmp(temp.name, list[k].name) < 0) { 17 | list[k + 1] = list[k]; 18 | k = k - 1; 19 | } 20 | } 21 | list[k + 1] = temp; 22 | } //end sort 23 | -------------------------------------------------------------------------------- /votes.txt: -------------------------------------------------------------------------------- 1 | Victor Taylor 2 | Denise Duncan 3 | Kamal Ramdhan 4 | Michael Ali 5 | Anisa Sawh 6 | Carol Khan 7 | Gary Owen 8 | 9 | 3 1 2 5 4 3 5 3 5 3 2 8 1 6 7 7 3 5 10 | 6 9 3 4 7 1 2 4 5 5 1 4 0 11 | -------------------------------------------------------------------------------- /wordFreq.in: -------------------------------------------------------------------------------- 1 | The quick brown fox jumps over the lazy dog. Congratulations! 2 | If the quick brown fox jumped over the lazy dog then 3 | Why did the quick brown fox jump over the lazy dog? 4 | -------------------------------------------------------------------------------- /wordFreq.out: -------------------------------------------------------------------------------- 1 | 'jumped' not added to table 2 | 'then' not added to table 3 | 'why' not added to table 4 | 'did' not added to table 5 | 'jump' not added to table 6 | 7 | Words Frequency 8 | 9 | brown 3 10 | congratulations 1 11 | dog 3 12 | fox 3 13 | if 1 14 | jumps 1 15 | lazy 3 16 | over 3 17 | quick 3 18 | the 6 19 | --------------------------------------------------------------------------------