diff options
feat(Week02): Add solutions
3 files changed, 59 insertions, 0 deletions
| -rw-r--r-- | Week02/Exercise03/intarray.cpp | 27 | ||||
| -rw-r--r-- | Week02/Exercise03/intarray.h | 15 | ||||
| -rw-r--r-- | Week02/Exercise03/main.cpp | 17 |
diff --git a/Week02/Exercise03/intarray.cpp b/Week02/Exercise03/intarray.cpp new file mode 100644 index 0000000..3d8853d --- /dev/null +++ b/Week02/Exercise03/intarray.cpp @@ -0,0 +1,27 @@ +#include "intarray.h" + +void IntArray::deleteSelf() { + delete[] elems; + + size = 0; + elems = nullptr; +} + +int IntArray::sum() { + int totalSum = 0; + for (unsigned i = 0; i < size; ++i) + totalSum += elems[i]; + return totalSum; +} + +IntArray newIntArray(unsigned size) { + IntArray ia; + ia.size = size; + ia.elems = new int[size]; + + return ia; +} + +void deleteIntArray(IntArray& arr) { + arr.deleteSelf(); +} diff --git a/Week02/Exercise03/intarray.h b/Week02/Exercise03/intarray.h new file mode 100644 index 0000000..9f1c0b0 --- /dev/null +++ b/Week02/Exercise03/intarray.h @@ -0,0 +1,15 @@ +#ifndef _INTARRAY +#define _INTARRAY + +struct IntArray { + unsigned size; + int* elems; + + void deleteSelf(); + int sum(); +}; + +IntArray newIntArray(unsigned size); +void deleteIntArray(IntArray& arr); + +#endif diff --git a/Week02/Exercise03/main.cpp b/Week02/Exercise03/main.cpp new file mode 100644 index 0000000..07f59fb --- /dev/null +++ b/Week02/Exercise03/main.cpp @@ -0,0 +1,17 @@ +#include <iostream> +#include "intarray.h" + +int main() { + unsigned N; + std::cin >> N; + + IntArray ia = newIntArray(N); + for (unsigned i = 0; i < ia.size; ++i) + std::cin >> ia.elems[i]; + + std::cout << ((double)ia.sum() / ia.size) << std::endl; + + deleteIntArray(ia); + + return 0; +} |
