
Problem :
Sum of All Array Elements – Using Recursion
int sumArray(int arr[], int n, int index) {
if(index == n) // Base case
return 0;
return arr[index] + sumArray(arr, n, index + 1); // Recursive call
}
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
total = sumArray(arr, n, 0);<br><br>#include <stdio.h>
// Function to find sum of array elements using recursion
int sumArray(int arr[], int n, int index) {
if(index == n)
return 0;
return arr[index] + sumArray(arr, n, index + 1);
}
int main() {
int n, i, total;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
total = sumArray(arr, n, 0);
printf("\nSum of all array elements: %d", total);
return 0;
}
Enter the number of elements: 5
Enter the elements:
1 2 3 4 5
Sum of all array elements: 15
Enter the number of elements: 4
Enter the elements:
10 -2 5 7
Sum of all array elements: 20