Description: Sum values in an array
Enter array length, followed by return, followed by values,
separating values by blanks. For example: 3<return>1 2 3 => {1, 2, 3}
1
2
3
4
5
6
7
8
9
10
| > 3
1 2 3
6
> 8
10 20 30 40 5 6 7 8
126
> 49
238 514 296 1247 710 1115 921 463 453 494 169 682 90 673 575 1273 71
898 92 549 912 1099 721 1186 46 290 471 946 1088 45 850 26 549 1136
1263 1250 951 884 412 103 77 572 775 157 1236 49 130 1298 938 30983
|
1
2
3
| #include <stdio.h>
#include <string.h>
#include "../lib/unity/src/unity.h" // throwtheswitch.org
|
Solution
1
2
3
4
5
6
7
| long sum(const int * arr, const int arrlen) {
long sum = 0;
for (int i = 0; i < arrlen; i++) {
sum += arr[i];
}
return sum;
}
|
Tests
1
2
3
4
5
6
7
8
9
10
| void test_sum(void) {
int arr[] = {10, 20, 30, 40, 5, 6, 7, 8};
TEST_ASSERT_EQUAL_INT(126, sum(arr, 8));
}
int run_tests(void) {
UNITY_BEGIN();
RUN_TEST(test_sum);
return UNITY_END();
}
|
Interaction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| int main(int argc, char *argv[]) {
run_tests();
if (argc > 1 && !strcmp(argv[1], "-i")) {
printf("Enter array length, followed by return, followed by "
"values,\nseparating values by blanks. For example: "
"3<return>1 2 3 => {1, 2, 3}\n> ");
int arrlen;
while (1) {
scanf("%d\n", &arrlen);
int arr[arrlen];
int i = 0, c = 0;
char temp;
while (scanf("%d%c", &arr[i], &temp)) {
i++, c++;
if (temp == '\n') break;
}
if (c != arrlen) {
printf("You did not enter exactly %d values.\n"
"Result will not be accurate.\n",
arrlen);
}
printf("%ld", sum(arr, arrlen));
printf("\n> ");
}
}
}
|