Accumulation AlgorithmThe accumulation algorithm in C language is one of its fundamental algorithms, primarily used to sum values through looping methods, such as using a for loop to calculate the sum of all elements in a known array (it seems that the standard library in C does not have built-in methods for summing arrays).In some higher-level programming languages, there may be built-in functions to sum elements of arrays or similar sequences, such as the built-in sum() function in Python and the array_sum() function in PHP (although many languages do not seem to have such built-in functions).C Language Accumulation Algorithm ExampleThe following example mainly introduces the accumulation algorithm in C language using two looping methods: the for loop and the while loop:
#include <stdio.h>// for loopint sumArray_for(int arr[], int size){ int sum = 0; for (int i = 0; i < size; i++) { sum += arr[i]; } return sum;}// while loopint sumArray_while(int arr[], int size){ int sum = 0; int i = 0; while (i < size) { sum += arr[i]; i++; } return sum;}int main() { int numbers[] = {1, 2, 3, 4, 5}; int size = sizeof(numbers) / sizeof(numbers[0]); int sum_for = sumArray_for(numbers, size); int sum_while = sumArray_while(numbers, size); printf("for loop calculated the total sum of array elements: %d; while loop calculated: %d\n", sum_for, sum_while); return 0;}
The code compiles and runs, producing the output:
for loop calculated the total sum of array elements: 15; while loop calculated: 15
Disclaimer: The content is for reference only, does not guarantee accuracy, and should not be used as the basis for any decisions!