How to calculate the sum of elements in an array using the C language?

To find the sum of elements in an array, you can achieve this by using a loop to iterate through the array and accumulate the elements.

The sample code is as follows:

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;

    // 遍历数组并累加元素的值
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }

    printf("数组元素的和为: %d\n", sum);

    return 0;
}

Running the above code will output:

数组元素的和为: 15

In the code, an integer array arr is first defined. The length of the array is obtained using the sizeof operator, and the number of elements in the array, size, is calculated. Then, a loop is used to iterate through the array, adding each element’s value to the sum variable each time. Finally, the value of sum is outputted, which is the sum of the elements in the array.

bannerAds