Logical operator || in C # does not work [closed]

2

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

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");
        }

    }
}
    
asked by anonymous 19.04.2017 / 17:27

3 answers

9

The problem is that you are putting ; into if and you are closing it. The correct 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");
            }
        }
    }
}

See working on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

    
19.04.2017 / 17:37
3

Your if statement is being terminated on the first line, since it has ; with it, the two MessageBox are called sequentially.

One palliative solution to this scenario is the use of Linq , a>:
Note: If the intention is to display a user message to each occurrence, then disregard.

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

With Linq you can:

  • Create a list with the number of sequential numbers you want;
  • Filter directly on this list, according to your conditions;
19.04.2017 / 17:49
1

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

    
19.04.2017 / 17:34