Prime search does not work

Warning: Simple homework, I don’t know what I am doing

So, I'm trying to create a program that will find the first primes from 1 to 100 and print them in a list. This is my code:

private bool IsPrime(int number) { int count; if (number == 2) return true; for (count = 3; count < number; count = count + 2) { if (number % count == 0) return false; } return true; } private void calculateButton_Click(object sender, EventArgs e) { int number; for (number = 1; number < 100; number = number++) if (IsPrime(number)) primeList.Items.Add(number); } 

And the program does not catch any syntax errors, but it also freezes every time I try to run it. Any idea why this is happening? Thanks.

+4
source share
1 answer

You're using:

 for (number = 1; number < 100; number = number++) 

while you have to write

  for (number = 1; number < 100; number++) 

You should read these articles to understand why your source code did not increase: for , ++ Operator

In some test code, you can find out the behavior of the ++ operator:

  int n = 0; Console.WriteLine(n); //0 n = n++; Console.WriteLine(n); //0 n = ++n; Console.WriteLine(n); //1 n = n++; Console.WriteLine(n); //1 n = ++n; Console.WriteLine(n); //2 

Another nice example:

  int n = 0; int x = n++; int y = ++n; Console.WriteLine(string.Format("x={0}", x)); //0 Console.WriteLine(string.Format("y={0}", y)); //2 Console.WriteLine(x + y); //n++ + ++n == 0 + 2 == 2 n = 0; x = ++n; y = n++; Console.WriteLine(string.Format("x={0}", x)); //1 Console.WriteLine(string.Format("y={0}", y)); //1 Console.WriteLine(x + y); //++n + n++ == 1 + 1 == 2 
+9
source

Source: https://habr.com/ru/post/1437914/


All Articles