Logical operator || in C# does not work

Asked

Viewed 191 times

2

I’m trying to do an exercise where in a range of 0 to 30 I want to know which numbers are divisible by 3 or 4. Working with a if for every situation works. But if I try to use the logical operator || does not work. It is part of the code that is commented.

private void button5_Click(object sender, EventArgs e)
{
    int iA;

    for (iA = 0; iA <= 30; iA++)
    {
        //if (iA % 3 == 0 || iA % 4 == 0);
        //{
        //    MessageBox.Show(iA + " é múltiplo de 3 ou de 4");
        //}
        if (iA % 3 == 0)
        {
            MessageBox.Show(iA + " é múltiplo de 3");
        }
        else if (iA % 4 == 0)
        {
            MessageBox.Show(iA + " é múltiplo de 4");
        }

    }
}
  • Typo is not within the scope of the SE

  • 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.

3 answers

9

The problem is that you’re putting one ; in the if and is closing it. The right thing would be:

using static System.Console;

public class Program {
    public static void Main() {
        for (var iA = 0; iA <= 30; iA++) if (iA % 3 == 0 || iA % 4 == 0) WriteLine(iA + " é múltiplo de 3 ou de 4");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

3

Your instruction if is being shut down on the first line, as it has a ; with that, the two MessageBox are called sequentially.


A palliative solution to this scenario is with the use of Linq:
Obs: If the intention is to display a message to the user at each occurrence, then disregard.

var listaNumeros = Enumerable.Range(1, 30).Where(p => p % 3 ==0 || p % 4 == 0).ToList();

With the Linq you can:

  • Create a list of how many sequential numbers you want;
  • Filter directly into this list according to your conditions;

1

I found the error. The if structure does not end with ";". Thankful

  • Mark the answer as correct.

  • 1

    Accept the answer that best met your need.

Browser other questions tagged

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