📌  相关文章
📜  C / C++程序,用于查找给定数组中元素的总和

📅  最后修改于: 2021-05-28 04:20:37             🧑  作者: Mango

给定整数数组,找到其元素的总和。

例子 :

Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50
C/C++
/* CPP 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[0]);
    printf("Sum of given array is %d", sum(arr, n));
    return 0;
}
Please refer complete article on Program to find sum of elements in a given array for more details!Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.