# C Program to Find the Sum of Elements of an Array

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

Recommended Practice

## C

 `/* C Program to find sum of elements` ` ``in a given array */` `#include `   `// 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);` `    ``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 ` `#include ` `#include `   `// 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 + sum(arr + 1, n - 1);` `    ``}` `}`   `int` `main()` `{` `    ``int` `arr[] = { 12, 3, 4, 15 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);`   `    ``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 ` `#include ` `#include `   `int` `main()` `{` `    ``int` `vec[] = { 12, 3, 4, 15 };` `    ``int` `n = ``sizeof``(vec) / ``sizeof``(vec);`   `    ``// storing all the prefix here` `    ``int` `prefix[n];` `    ``// pushing the first element of the vec array` `    ``// into the prefix array` `    ``prefix = vec;`   `    ``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.

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!

Previous
Next