From 5eb4931002d564d6f07e110dc2f7be064755d322 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Sun, 10 Mar 2019 18:39:51 -0400 Subject: [PATCH] Added getSum and getProd functions --- DynamicInt64Array.h | 24 ++++++++++++++++++++++++ testDynamicInt64Array.c | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/DynamicInt64Array.h b/DynamicInt64Array.h index 51c5f21..92fbe17 100644 --- a/DynamicInt64Array.h +++ b/DynamicInt64Array.h @@ -298,4 +298,28 @@ bool isSortedDynamicInt64Array(struct DynamicInt64Array* ary){ return true; } +//This function returns the sum of all elements in a DynamicInt64Array +int64_t getSumDynamicInt64Array(struct DynamicInt64Array* ary){ + int64_t sum = 0; + //Look through every element in the array, adding the numbers to a running sum + for(uint64_t location = 0;location < ary->size;++location){ + sum += ary->ptr[location]; + } + + //Return the sum + return sum; +} + +//This function returns the product of all elements in a DynamicInt64Array +int64_t getProdDynamicInt64Array(struct DynamicInt64Array* ary){ + int64_t product = 1; + //Look through every element in the array, multiplying it + for(uint64_t location = 0;location < ary->size;++location){ + product *= ary->ptr[location]; + } + + //Return the product + return product; +} + #endif //DYNAMIC_ARRAY_H diff --git a/testDynamicInt64Array.c b/testDynamicInt64Array.c index bd34ef6..1bf84af 100644 --- a/testDynamicInt64Array.c +++ b/testDynamicInt64Array.c @@ -154,6 +154,30 @@ int main(){ return 1; } + //Test the getProd function + if(getSumDynamicInt64Array(&testAry) == 21){ + printf("getSum is working correctly\n"); + } + else{ + printf("There is something wrong with getSum\nThe sum returned is %d\nThe sum should be %d", getSumDynamicInt64Array(&testAry), 21); + return 1; + } + + //Test the getSum function + if(getProdDynamicInt64Array(&testAry) != 0){ + printf("There is something wrong with getProd\nThe product returned is %d\nThe product should be%d", getProdDynamicInt64Array(&testAry), 0); + return 1; + } + //Pop off the first 0 so there will be a number in the product + removeDynamicInt64Array(&testAry, 0); + if(getProdDynamicInt64Array(&testAry) == 720){ + printf("getProd is working correctly\n"); + } + else{ + printf("There is something wrong with getProd\nThe product returned is %d\nThe product should be%d", getProdDynamicInt64Array(&testAry), 720); + return 1; + } + //Release all of the memory allocated by the array destroyDynamicInt64Array(&testAry);