forked from hermanwongkm/CS1010
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumArray.c
54 lines (42 loc) · 974 Bytes
/
sumArray.c
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// sum_array_recursion.c
// Sum up all values in an integer array.
#include <stdio.h>
#define MAX_SIZE 10
int readArray(int []);
void printArray(int [], int);
int sumArray(int [], int);
int main(void) {
int list[MAX_SIZE], size;
size = readArray(list);
printArray(list, size);
printf("Sum = %d\n", sumArray(list, size));
return 0;
}
// Read values into array.
// Return number of elements read.
int readArray(int arr[]) {
int size, i;
printf("Enter number of elements: ");
scanf("%d", &size);
printf("Enter %d values: ", size);
for (i=0; i<size; i++)
scanf("%d", &arr[i]);
return size;
}
// Print values in array
void printArray(int arr[], int size) {
int i;
printf("Array read: ");
for (i=0; i<size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Sum all the values in the array arr
// Pre-cond: size >= 0
int sumArray(int arr[], int size) {
if(size == 1 || size == 0)
return *arr;
else{
return arr[size-1] + sumArray(arr, size-1);
}
}