Home > Article > Backend Development > Summing method in c language
Two methods for summation in C language: Use for loop: suitable for situations where the array is small or flexibility is required. Using pointers: Suitable for situations where the array is large or efficiency needs to be improved.
Sum method in C language
There are many methods for summation in C language, the specific choice depends on Depending on the size of the array, data type and required efficiency. The two most commonly used summation methods are introduced below:
Using a for loop
int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; }
Where:
sum
is a variable used to store the sum, initialized to 0. arr
is the array to be summed. n
is the size of the array. Use pointers to elements
int sum = 0; int *ptr = arr; for (int i = 0; i < n; i++) { sum += *ptr; ptr++; }
where:
sum
and n
Same as above. ptr
is a pointer to the first element of the array, initialized using arr
. *ptr
Dereference pointer to access the value of the current element. Choose a method
for
loop is usually simpler and faster. float
or double
), you need to modify the data type declaration in the code accordingly. The above is the detailed content of Summing method in c language. For more information, please follow other related articles on the PHP Chinese website!