In this article, we will go through code examples which help in finding sum of all elements present in an array. The intent of this article is to help understand various concepts in arrays, so we avoid using ready made functions like sum
etc and instead use array iteration/traversal to find out the sum.
#include <stdio.h>
int main() {
// Create an array with numbers
int numbers[] = {1, 2, 3, 4, 5};
// Calculate the number of elements in the array
int count = sizeof(numbers) / sizeof(numbers[0]);
// Initialize a variable to store the sum
int sum = 0;
// Loop through each number in the array
for (int i = 0; i < count; i++) {
// Add the current number to the sum
sum += numbers[i];
}
// Display the sum of all numbers in the array
printf("The sum of all numbers in the array is: %d\n", sum);
return 0;
}