0
for (int i=2; i<=upperBound; i++) {
    if (num % i ==0)
        printf(""%d" is a prime number.");
}

I understand that I should know this stuff but I'm just starting to learn C and it's a bit confusing. I know that the condition is supposed to be in the middle, that's why I'm not sure how to include the upperbound variable.

Jason
  • 2,493
  • 2
  • 27
  • 27
toaster
  • 1
  • 2
  • 5
    The first line of your question is the answer to your question. The rest of your logic is wrong. For example, the first iteration of your loop will claim a number is prime if it's even. – David Schwartz Feb 28 '23 at 17:56
  • The line `printf(""%d" is a prime number.");` does not compile, and anyway, if `num` is exactly divisible by `i` (without a remainder) then `num` *isn't* prime, and there is no point continuing with the loop. – Weather Vane Feb 28 '23 at 17:58
  • Your algorithm is backwards. You want to stop (and return 0) if `(num % i) == 0`. Test 2 separately and then do `i += 2` so you only test _odd_ numbers. Try: `int isprime(int num) { if ((num % 2) == 0) return 0; for (int i = 3; i <= upperBound; i += 2) { if ((num % i) == 0) return 0; } return 1; }` – Craig Estey Feb 28 '23 at 18:21
  • Does this answer your question? [What is the full "for" loop syntax in C?](https://stackoverflow.com/questions/276512/what-is-the-full-for-loop-syntax-in-c) – nielsen Feb 28 '23 at 18:49
  • The printf line should be `printf("%d is a prime number.", num);` in which the `num` variable will replace the `%d` when printing – Torge Rosendahl Feb 28 '23 at 20:02
  • Welcome to StackOverflow! Please take the [tour] to learn how this site works, and read "[ask]". -- I do not understand your question in the title, as your code is the answer. Please clarify by [edit]ing your question. What is the specific issue? – the busybee Feb 28 '23 at 21:07

1 Answers1

0

Your loop already behaves as requested.

for (int i=2; i<=upperBound; i++) {
   ...
}

is roughly equivalent to

int i=2;
while (i<=upperBound) {
   ...
   i++;
}
  1. In the first pass of the loop, i is 2.
  2. In the second, 3.
  3. In the last pass, i will be equal to upperBound.

At the end of that pass, i becomes equal to upperBound+1, so i<=upperBound is no longer true, so the loop exits.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • @Eric Postpischil That would be true, except `i` is scoped to the `for` loop. It doesn't equal `upperBound+1` after the loop because it doesn't exist. That is one of the differences between the two snippets. The other is how it behaves if the loop uses `continue`. – ikegami Feb 28 '23 at 18:28
  • Yes, I was looking at your `while`. – Eric Postpischil Feb 28 '23 at 18:29