Reputation: 11
I have this piece of code that is supposed to sum all the even numbers but it isnt working
int n, k = 0, sum = 0;
for (i = 0; i < n; i++)
if (s[i] % 2 == 0) {
k++;
for (int i = 0; i < n; i++)
sum += s[i];
printf("%i ", s[i]);
}
printf("\n sum of even numbers=%i", sum);
Upvotes: 1
Views: 267
Reputation: 17
There was no need for a nested loop. Just delete the inner for
Upvotes: 0
Reputation: 844
int i, sum = 0;
for (i=0; i < n; i++) //n is the number of elements in the array
{
if (s[i] % 2 == 0)
sum = sum + s[i];
}
printf("Sum of the even numbers = %d",sum);
Upvotes: 1