find the sum of all elements in an array in C
Code snippet on how to find the sum of all elements in an array in C
int arraySum(int arr[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
This code finds the sum of all elements in an array. The function takes two parameters: an array of integers (arr[]
) and the length of the array (n
). An integer sum
is initialized to 0, and a for
loop is used to iterate over the array. During each iteration, the value of the current array element is added to the sum
variable. After looping through all elements of the array, the sum
variable contains the sum of all elements, which is then returned as the result.