Complementary task for topic: 10
M Nemeth · 2023-08-29 15:21:04.633218'
Recursion: Array sum
Recursion: Array sum
Write a program to find the sum of elements in an array using recursion!
Hint:
Solution
#include
// Function to calculate the sum of elements in an array using recursion
int arraySum(int arr[], int size) {
if (size == 0) {
return 0;
} else {
return arr[size - 1] + arraySum(arr, size - 1);
}
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size <= 0) {
printf("Error: The size of the array should be greater than 0.\n");
return 1;
}
int arr[size];
printf("Enter %d elements of the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
int result = arraySum(arr, size);
printf("The sum of elements in the array is: %d\n", result);
return 0;
}