1. Member
Join Date
Aug 2009
Location
South Sweden
Posts
24
Rep Power
0

## 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:
Java Code:
```for (int k=2; k<tal; k++)
{
if (tal % k == 0)
{
Primtal = false;
}
}```
Here's my try at a while:
Java 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

2. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
10
Put
Java Code:
`k = k + 1;`
as the last line of the while.

3. Member
Join Date
Sep 2009
Posts
2
Rep Power
0
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.

4. Member
Join Date
Aug 2009
Location
South Sweden
Posts
24
Rep Power
0
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!

5. Member
Join Date
Sep 2009
Posts
6
Rep Power
0
refer examples on java2examples.com

6. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•