Reputation: 175
I want a WinFormApp to calculate the Prime numbers between 100 to 1000 and display them in a "lb" list box. But I'm facing with this error:
WinFormApp1.Form1.pn(int)': not all code paths return a value
bool pn(int n)
{
for (int j = 2; j <= n; j++)
{
if (n % j != 0)
return false;
return true;
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 100; i <= 1000; i++)
{
if (pn(i) == true)
lb.Items.Add(i);
}
}
Upvotes: 0
Views: 206
Reputation: 7
bool pn(int n)
{
for (int j = 2; j <= n; j++)
{
if (n % j == 0)
{
return false;
}
}
return true;
}
Upvotes: -1
Reputation: 113262
You simply placed your return true
inside the loop by mistake. As well as giving incorrect results, it the compiler can see that if the loop finishes, there'll be no value returned, hence the compile error.
bool pn(int n)
{
for (int j = 2; j <= n; j++)
{
if (n % j != 0)
return false;
}
return true;
}
Upvotes: 10