Given an array of integers, find the sum of its elements.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6Input : arr[] = {15, 12, 13, 10}
Output : 50
C
/* C Program to find sum of elements in a given array */
#include <bits/stdc++.h> // function to return sum of elements // in an array of size n int sum( int arr[], int n)
{ int sum = 0; // initialize sum
// Iterate through all elements
// and add them to sum
for ( int i = 0; i < n; i++)
sum += arr[i];
return sum;
} int main()
{ int arr[] = { 12, 3, 4, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "Sum of given array is %d" , sum(arr, n));
return 0;
} |
Output
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
Another Method#2: Using Recursion
C
/* C++ Program to find sum of elements in a given array using recursion */ #include <stdio.h> #include <stdlib.h> #include <string.h> // function to return sum of elements // in an array of size n int sum( int arr[], int n)
{ // base case
if (n == 0) {
return 0;
}
else {
// recursively calling the function
return arr[0] + sum(arr + 1, n - 1);
}
} int main()
{ int arr[] = { 12, 3, 4, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , sum(arr, n));
return 0;
} |
Output
34
Time Complexity: O(n)
Auxiliary Space: O(n)
Another Method#3: Using prefix sum
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main()
{ int vec[] = { 12, 3, 4, 15 };
int n = sizeof (vec) / sizeof (vec[0]);
// storing all the prefix here
int prefix[n];
// pushing the first element of the vec array
// into the prefix array
prefix[0] = vec[0];
for ( int i = 1; i < n; i++) {
// calculating the further prefix sum
int temp = prefix[i - 1] + vec[i];
prefix[i] = temp;
}
// last element of the prefix array
// will the sum of all elements of the
// vec array
printf ( "%d\n" , prefix[n - 1]);
return 0;
} |
Output
34
Time Complexity: O(n)
Auxiliary Space: O(n), for recursive stack space.