From 442a49ad5a48d417345959b903ae6a6d32d55759 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Fri, 15 Apr 2022 15:51:30 -0500 Subject: Great C programming fun Excellent fundamentals and displine training, many tools and techniques exercises: gdb, emacs, valgrind, git --- 14_array_max/arrayMax.c | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 14_array_max/arrayMax.c (limited to '14_array_max/arrayMax.c') diff --git a/14_array_max/arrayMax.c b/14_array_max/arrayMax.c new file mode 100644 index 0000000..5fc5d62 --- /dev/null +++ b/14_array_max/arrayMax.c @@ -0,0 +1,56 @@ +#include +#include + +int * arrayMax(int * array, int n) { + if (n == 0){ + return NULL; + } + int maxInt = array[0]; + int * answer = array; + for (int i = 1; i < n; i++) { + if (array[i] > maxInt) { + maxInt = array[i]; + answer = &array[i]; + } + } + return answer; +} + +void doTest(int * array, int n) { + printf("arrayMax("); + if (array == NULL) { + printf("NULL"); + } + else { + printf("{"); + for (int i =0; i < n; i++) { + printf("%d", array[i]); + if (i < n -1) { + printf(", "); + } + } + printf("}"); + } + printf(", %d) is \n", n); + int * p = arrayMax (array, n); + if (p == NULL) { + printf("NULL\n"); + } + else { + printf("%d\n", *p); + } +} + +int main(void) { + int array1[] = { 77, 33, 19, 99, 42, 6, 27, 4}; + int array2[] = { -3, -42, -99, -1000, -999, -88, -77}; + int array3[] = { 425, 59, -3, 77, 0, 36}; + + doTest (array1, 8); + doTest (array2, 7); + doTest (array3, 6); + doTest (NULL, 0); + doTest (array1, 0); + + return EXIT_SUCCESS; +} -- cgit v1.2.3