Like looks like an exercise, it may be "mandatory" to iterate one by one and use the operator %
(and there the another answer I’ve told you how to do).
But you can do a little better. Just make sure you’re starting with an even number, and then just iterate from 2 to 2:
// ... ler val1 e val2
int n = val1;
// se o valor inicial é ímpar, soma 1 para que ele seja par
if (n % 2 != 0)
n++;
// agora eu sei que n é par, então posso fazer o for de 2 em 2
int cont = 0;
for(; n <= val2; n += 2) {
printf("%d\n", n);
cont++;
}
printf("Entre os valores %d e %d existem %d números pares.\n", val1, val2, cont);
That is, if val1
is odd, I add 1 so that the for
start at an even number. And as I have now ensured that it always starts at an even number, I can do the for
by 2 (i.e., n += 2
). So I just use the operator %
once, before the loop (instead of iterating through all the numbers, one by one, and using %
for all).
And see that in the first expression inside the for
you don’t need to put val1
"loose" there, can leave empty even (if you are not going to do anything, do not put anything).
How do you want to print val1
in the end, so you can’t change it in the loop, so I used another variable for this (in this case, the n
).
Although, if it was just to know the amount, you don’t even have to keep counting. After all, come on a
and b
(provided that a
be even), the amount of even numbers is ((b - a) / 2) + 1
. The loop is only necessary to print the numbers. That is:
int n = val1;
// se o valor inicial é ímpar, soma 1 para que ele seja par
if (n % 2 != 0)
n++;
// não precisa contar dentro do loop
int cont = ((val2 - n) / 2) + 1;
// agora eu sei que n é par, então posso fazer o for de 2 em 2
for(; n <= val2; n += 2) {
printf("%d\n", n);
}
printf("Entre os valores %d e %d existem %d números pares.\n", val1, val2, cont);