#include <stdio.h> #include <stdlib.h> #include <string.h> // Compare two strings representing numbers. int numcmp(const char* s1, const char* s2) { float v1 = atof(s1); // Convert a string to an float, e.g. "3.14" to 3.14. float v2 = atof(s2); if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } // Compare two strings representing numbers, using absolute values of the numbers. int absnumcmp(const char* s1, const char* s2) { float v1 = atof(s1); float v2 = atof(s2); if (v1 < 0) { v1 = -v1; } if (v2 < 0) { v2 = -v2; } if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } // Find the position (index) of the "minimum" item in the given string array, // using (*comp) as the way to compare strings. int minpos(char* array[], int len, int (*comp)(const char*, const char*)) { int index_min = 0; // Assumes len >= 1 for (int i = 1; i < len; i++) { if ((*comp)(array[i], array[index_min]) < 0) { index_min = i; } } return index_min; } void main() { char* numbers[] = {"3.14", "-0.618", "2.222", "9.9", "3", "1.618", "17.23", "-12.345", "2.718", "10"}; char* produce[] = {"Carrot","Asparagus","Eggplant","Apple","Banana","Durian"}; int numbers_minpos = minpos(numbers, 10, numcmp); printf("The minimum number is %s at position %d.\n", numbers[numbers_minpos], numbers_minpos); int numbers_absminpos = minpos(numbers, 10, absnumcmp); printf("The minimum |number| is %s at position %d.\n", numbers[numbers_absminpos], numbers_absminpos); int produce_minpos = minpos(produce, 5, strcmp); // Use built-in strcmp for alphabetic compare! printf("The alphabetically first produce is %s at position %d.\n", produce[produce_minpos], produce_minpos); }