Complementary task for topic: 3
M Nemeth · 2023-08-29 15:21:04.615220'
Arrays: summation
Arrays: summation
Write a C program that calculates the sum of elements in an integer array and displays the result.
Hint: When we use static arrays we know the size, so usually it is comfortable to use a for loop to traverse.
Solution
#include
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Initialize the array with values
int sum = 0;
for (int i = 0; i < SIZE; i++) {
sum += numbers[i]; // Accumulate the sum of array elements
}
printf("Sum of the array elements: %d\n", sum);
return 0;
}
Explanation
In this example, the program initializes an integer array numbers with the values {10, 20, 30, 40, 50}. The size of the array is specified using the 5. That is not neccessary, the compiler calculates the size before compiling the code. (see task before) The program then uses a for loop to iterate over the array and accumulate the sum of its elements. The sum variable is used to keep track of the running total. Finally, the program displays the sum of the array elements using printf().