summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/14.2.c
diff options
context:
space:
mode:
authorTobias Klauser <tklauser@distanz.ch>2008-01-27 11:37:44 +0100
committerTobias Klauser <tklauser@xenon.tklauser.home>2008-01-27 11:37:44 +0100
commit7e0f021a9aec35fd8e6725e87e3313b101d26f5e (patch)
treeb1cacc4b24393f517aeb4610e9e1021f954307a8 /reference/C/CONTRIB/OR_USING_C/14.2.c
Initial import (2.0.2-6)2.0.2-6
Diffstat (limited to 'reference/C/CONTRIB/OR_USING_C/14.2.c')
-rw-r--r--reference/C/CONTRIB/OR_USING_C/14.2.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/reference/C/CONTRIB/OR_USING_C/14.2.c b/reference/C/CONTRIB/OR_USING_C/14.2.c
new file mode 100644
index 0000000..07418aa
--- /dev/null
+++ b/reference/C/CONTRIB/OR_USING_C/14.2.c
@@ -0,0 +1,75 @@
+#include <stdio.h>
+
+#define NSTRS 10 /* number of strings */
+#define STRLEN 16 /* length of each string */
+
+char strs[NSTRS][STRLEN]; /* array of strings */
+
+main()
+{
+ int i;
+ extern int compare1(), compare2();
+
+ /*
+ * Prompt the user for NSTRS strings.
+ */
+ for (i = 0; i < NSTRS; i++) {
+ printf("Enter string #%d: ", i);
+ gets(strs[i]);
+ }
+
+ /*
+ * Sort the strings into ascending order. There
+ * are NSTRS array elements, each one is STRLEN
+ * characters long. Note we give the size of
+ * the array element, not the length of the
+ * string in it.
+ */
+ qsort(strs, NSTRS, STRLEN, compare1);
+
+ /*
+ * Print the strings.
+ */
+ printf("\nSorted in ascending order:\n");
+
+ for (i = 0; i < NSTRS; i++)
+ printf("\t%s\n", strs[i]);
+
+ /*
+ * Now sort the strings in descending order.
+ */
+ qsort(strs, NSTRS, STRLEN, compare2);
+
+ printf("\nSorted in descending order:\n");
+
+ for (i = 0; i < NSTRS; i++)
+ printf("\t%s\n", strs[i]);
+
+ exit(0);
+}
+
+/*
+ * compare1--compare a and b, and return less than,
+ * greater than, or equal to zero. Since
+ * we are comparing character strings, we
+ * can just use strcmp to do the work for us.
+ */
+compare1(a, b)
+char *a, *b;
+{
+ return(strcmp(a, b));
+}
+
+/*
+ * compare2--this compares a and b, but is used for
+ * sorting in the opposite order. Thus it
+ * returns the opposite of strcmp. We can
+ * simulate this by simply reversing the
+ * arguments when we call strcmp.
+ */
+compare2(a, b)
+char *a, *b;
+{
+ return(strcmp(b, a));
+}
+