Valerie Meunier

Valerie Meunier

  • 1.6k
  • 533
  • 25.4k

Why is this loop executed?

Aug 21 2021 2:25 PM

Hi

I don't understand why the result of this code is "3 is a prime number". 

Variabel i in the for ... start at 3/2 = 1 (because of int). So according to me, the loop should never be executed because the condition is i > 1 and this is never satisfied.. But, as i said, this code gives "3 is a prime number" (and of course that's right).

Same with value x= 2 ("2 is not a prime number").

Thanks.

static void Main(string[] args)
    {
       int x = 3;
        string f = "";
        for (int i = x / 2; i > 1; i--)
        {
            if (x % i == 0)
            {
                f = "not a";
                break;
            }
            else
                f = "a";
        }
        Console.WriteLine("{0} is " + f + " prime number", x);
    }


Answers (2)