There are several problems with that code. I gave an organized and made the code more idiomatic to get used to (it’s not enough to work, you have to learn how to actually make code in production) and solved most of them. Of course, not everyone will make obvious mistakes, but they will in certain situations.
using static System.Console;
public class Program {
public static void Main() {
if (!int.TryParse(ReadLine(), out var n)) return;
var numeros = new int[n];
string[] entrada = ReadLine().Split(' ');
for (var i = 0; i < n; i++) {
if (!int.TryParse(entrada[i], out var valor)) return;
numeros[i] = valor;
}
var quantidade = 0;
for (var i = 0; i < n; i++) {
if (numeros[i] % 2 == 0) {
Write($"{numeros[i]} ");
quantidade++;
}
}
WriteLine();
WriteLine(quantidade);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I tested the values before using because if one enters something wrong the application will break. I preferred only to leave in this case but you could give a message indicating the error. How future exercise can make the data be asked again instead of terminating the application normally.
To ask for data all in one line is only to ask for trouble, initially I thought until the exercise asked for it and I did so, but in fact it does not even ask, it just showed the data that will be entered. In the same way that the output does not have a specific format, so it breaks line or doesn’t even matter much. I would change that to read each data individually.
Anyway I used the Write()
instead of the WriteLine()
not to jump the line, but I gave it some space. I used the interpolation in these cases to learn the form, but in fact it is not even necessary in such a simple case, if doing with concatenation is good. Without the space everything will be piled up.
Note the smaller number of lines without impairing readability.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero