Welcome to the forum! Thank you for being so clear with your question. You explained what the program should do, gave several examples, posted the incorrect output and included your code. These are exactly the things that will get you quick results.
The one thing that you could do better is to use code tags when posting your code. To do this, highlight the code while creating (or editing) the post and click the "<>" button on the right side of the edit window.
To answer your question, take a look at isPrime() when I indent the code to match the actual structure:
1 2 3 4 5 6 7 8 9 10 11
|
int
isPrime(int nr)
{
int i;
for (i = 2; i <= nr / 2; i++)
if (nr % i == 0)
return 0;
else
return true;
}
|
Notice that the "return true" is
inside the loop. That means that isPrime() always returns on the very first time through the loop, depending on whether nr%i is zero.
To fix this, you want to return true only if you make it out of the loop:
1 2 3 4 5 6 7 8 9 10 11
|
int
isPrime(int nr)
{
int i;
for (i = 2; i <= nr / 2; i++) {
if (nr % i == 0) {
return 0;
}
}
return true;
}
|
Some other suggestions:
Notice that I used braces even though there is only one statement inside the
for
loop, and even though there is only one statement inside the
if
. This ensures that if I decide to put another statement in there, the code will still work properly. Trust me, if you don't do this, you'll spend hours trying to track down a bug where you've indented the code one way, but the actual block structure is something different.
Use the for loop in FirstPrimeNumber:
1 2 3 4 5 6 7 8
|
int
FirstPrimeNumber(int N)
{
for (int nrNow = N+1; ; mrNow++) { // empty condition part is the same as "true"
if (isPrime(nrNow))
return nrNow;
}
}
|
Your code is inefficient, but I suspect that efficiency wasn't the point of this exercise.