For to while?

• 09-08-2009, 10:21 AM
Mattedatten
For to while?
Hey all
I'm trying to do a school exercise in java, and I fail at it, but it seems like my teacher doesnt know what's wrong.

I want to do a "for" to a "while"
(Primtal == true earlier in the code)
Here's the for:
Code:

```for (int k=2; k<tal; k++) {         if (tal % k == 0)         {                 Primtal = false;         } }```
Here's my try at a while:
Code:

```int k = 2; while(k < tal) {         k = k + 1;                                if (tal % k == 0)         {                 Primtal = false;         }                                         }```
I dont get the while "primtal" to become false, when the for does get "primtal" to false...
Any help?
///Mattedatten
• 09-08-2009, 10:24 AM
r035198x
Put
Code:

`k = k + 1;`
as the last line of the while.
• 09-08-2009, 10:27 AM
zellazode
the problem is the line:
k = k + 1

you do it before the test "if" - and so on your first entrance to the loop, you check it for k = 3.

In the for loop, k++ doesn't happen til you finish one iteration of the loop, and so in that first iteration k=2 and "if" is checked on this k. only after the iteration ends, k++ occurs.

So, just move k=k+1 to after the if-block.
• 09-08-2009, 10:36 AM
Mattedatten
Quote:

Originally Posted by zellazode
the problem is the line:
k = k + 1

you do it before the test "if" - and so on your first entrance to the loop, you check it for k = 3.

In the for loop, k++ doesn't happen til you finish one iteration of the loop, and so in that first iteration k=2 and "if" is checked on this k. only after the iteration ends, k++ occurs.

So, just move k=k+1 to after the if-block.

Wow, that's an fast answer, and easy solution :) Thanks!
• 09-08-2009, 12:44 PM
phoenix123
refer examples on java2examples.com
• 09-08-2009, 02:28 PM
Fubarable
phoenix, all of your posts have such similarity as to suggest that you're spamming answers with plugs to a web site. Please be careful with this as this could lead to sanctions.