Warning: Simple homework assignment, no idea what I'm doing
So, I'm trying to make a program that finds the first prime numbers from 1 to 100 and prints them in a listbox. 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 isn't catching any syntax errors, but it also freezes up every time I try to run it. Any idea why this happens? Thanks.
You use:
for (number = 1; number < 100; number = number++)
while you should write
for (number = 1; number < 100; number++)
You should read these articles to understand why your original code didn't increment the : for, ++ Operator
You can learn the behaivour of the ++
operator in some test code:
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 would be:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With