Given an array of integers, find the sum of its elements.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6
Input : arr[] = {15, 12, 13, 10}
Output : 50
C
#include <bits/stdc++.h>
int sum( int arr[], int n)
{
int sum = 0;
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sum( int arr[], int n)
{
if (n == 0) {
return 0;
}
else {
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;
}
|
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]);
int prefix[n];
prefix[0] = vec[0];
for ( int i = 1; i < n; i++) {
int temp = prefix[i - 1] + vec[i];
prefix[i] = temp;
}
printf ( "%d\n" , prefix[n - 1]);
return 0;
}
|
Time Complexity: O(n)
Auxiliary Space: O(n), for recursive stack space.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 May, 2023
Like Article
Save Article