C Program to Find Array Sum

Here is a sample code that can be used to calculate the sum of an integer array.

#include <stdio.h>

// 定义求和函数
int sum(int arr[], int size) {
    int total = 0;
    for (int i = 0; i < size; i++) {
        total += arr[i];
    }
    return total;
}

int main() {
    int nums[] = {1, 2, 3, 4, 5};
    int size = sizeof(nums) / sizeof(nums[0]);
    int result = sum(nums, size);
    printf("数组的和为:%d\n", result);
    
    return 0;
}

In this code, we first define an integer variable total in the sum function to represent the sum of the array. Then we use a for loop to iterate through each element in the array and add it to total. Finally, we return this sum value. In the main function, we define an integer array nums and calculate its size. Then, we call the sum function, store the result of the array sum in the result variable, and print the result using the printf function.

bannerAds