From 0af2542ce5d2cdfc83cebd0c483a8e4c6a34b046 Mon Sep 17 00:00:00 2001 From: Hardik9991 <73008712+Hardik9991@users.noreply.github.com> Date: Sat, 17 Oct 2020 10:43:15 +0530 Subject: [PATCH] sum of elements Program to find sum of elements in a given array --- sum of elements | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 sum of elements diff --git a/sum of elements b/sum of elements new file mode 100644 index 00000000..e96858ed --- /dev/null +++ b/sum of elements @@ -0,0 +1,29 @@ +/* C++ Program to find sum of elements +in a given array */ +#include +using namespace std; + +// 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; +} + +// Driver code +int main() +{ + int arr[] = {12, 3, 4, 15}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Sum of given array is " << sum(arr, n); + return 0; +} + +// This code is contributed by rathbhupendra