Results 1 to 6 of 6

Thread: For to while?

  1. #1
    Mattedatten is offline Member
    Join Date
    Aug 2009
    Location
    South Sweden
    Posts
    24
    Rep Power
    0

    Default 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. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    Put
    Java Code:
    k = k + 1;
    as the last line of the while.

  3. #3
    zellazode is offline Member
    Join Date
    Sep 2009
    Posts
    2
    Rep Power
    0

    Default

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

    Default

    Quote Originally Posted by zellazode View Post
    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. #5
    phoenix123 is offline Member
    Join Date
    Sep 2009
    Posts
    6
    Rep Power
    0

    Default

    refer examples on java2examples.com

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    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
  •