Print values of a vector without line break

Asked

Viewed 491 times

1

Hello, I’m performing a C# exercise that asks for the following:

Entrada e Saída que deve ser usada

The output with even numbers should be presented without line break, but I do not understand how I can do this. My code is like this:

int N;
        N = int.Parse(Console.ReadLine());

        int[] numeros = new int[N];

        String[] entrada = Console.ReadLine().Split(' ');

        for (int i=0; i<N; i++)
        {
            numeros[i] = int.Parse(entrada[i]);
        }

        int quantidade;
        quantidade = 0;

        for (int i=0; i<N; i++)
        {

            if (numeros[i] % 2 == 0)
            {
                Console.WriteLine(numeros[i]);
                quantidade = quantidade + 1;
            }

        }
        Console.WriteLine(quantidade);
  • 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).

4 answers

4

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.

3

The function Console.WriteLine writes and breaks line.

In this case, use the function Console.Write, who just writes what you want.

Example:

Console.Write(numeros[i] + " ");
  • Hi Bruno, thanks for the answer! I tried with Console.Write and the numbers all came out without spacing between themselves, there is some way to fix this?

  • Yes, add a space after numeros[i] + " "

  • 1

    Perfect, thank you very much!

0

Only complementing, it is necessary to concatenate with another space, thus staying:

Console.Write(numeros[i] + " ");

0

Just for fun I did my version too :)

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        if (!int.TryParse(Console.ReadLine(), out var n)) return;

        var entrada = Console.ReadLine().Split(' ');

        if (entrada.Length != n)
        {
            Console.WriteLine($"Entrada deve ter {n} números e foram inseridos {entrada.Length}.");
            return;
        }

        try
        {
            var numerosPares = PegaPares(entrada);

            Console.WriteLine(string.Join(' ', numerosPares));
            Console.WriteLine(numerosPares.Count());
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private static IEnumerable<int> PegaPares(string[] numeros)
    {
        foreach (var numero in numeros)
        {
            if (!int.TryParse(numero, out var valor))
                throw new ArgumentException($"{numero} não é um número.");

            if (valor % 2 == 0)
                yield return valor;
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.