You are using the variable n
which was declared and not initialized, so it may have junk in memory and that junk value that was already there was used for sum. It makes no sense to use the value before asking the first time, changing the order of the code solves this. Then it takes advantage and declares the variable only in use, it is more readable and obvious (I always say that declaring before is confusing, but the staff always teaches this way because in the 70s it was like this).
#include <stdio.h>
int main() {
int nmrs, soma = 0;
printf("De quantos numeros quer fazer a soma? (impares serao desconsiderados)\n");
scanf("%d", &nmrs);
for (int i = 1; i <= nmrs; i++) {
int n;
printf("digite um numero: ");
scanf("%d", &n);
if (n % 2 == 0) soma += n;
}
printf("A soma dos numeros pares que aqui apareceram: %d", soma);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I haven’t changed your interpretation, but it may be that it is wrong. It may be that you should only count the pairs as well and your algorithm counts the odd ones. If you can’t count, you’d have to put one else
decreasing i
not to count the number that was dropped.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero