sum of list in C
Calculating the Sum of a List in C
To calculate the sum of a list in C, you can use a loop to iterate through each element of the list and add them together. Here's an example code snippet that demonstrates this:
#include <stdio.h>
int main() {
int list[] = {1, 2, 3, 4, 5};
int size = sizeof(list) / sizeof(list[0]);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += list[i];
}
printf("The sum of the list is: %d\n", sum);
return 0;
}
Let's break down the code and explain each step:
Include the necessary header file: In this case, we include the
<stdio.h>
header file, which provides the necessary functions for input and output operations.Declare and initialize the list: We declare an integer array called
list
and initialize it with some values. In this example, we have a list of integers:{1, 2, 3, 4, 5}
.Calculate the size of the list: We calculate the size of the list by dividing the total size of the list by the size of a single element. This is done using the
sizeof
operator.Initialize the sum variable: We declare an integer variable called
sum
and initialize it to 0. This variable will store the sum of the list elements.Iterate through the list: We use a
for
loop to iterate through each element of the list. The loop variablei
starts from 0 and goes up tosize - 1
.Add each element to the sum: Inside the loop, we add each element of the list to the
sum
variable using the+=
operator.Print the sum: Finally, we use the
printf
function to print the sum of the list.
When you run this code, it will output:
The sum of the list is: 15
This means that the sum of the elements in the list {1, 2, 3, 4, 5}
is 15.
I hope this explanation helps! Let me know if you have any further questions.