Thread: Do-while loop

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    1
    Rep Power
    0

    Do-while loop


    Hello everybody!

    I have a problem with the usage of do-while loop in code blocks.

    The problem is that it somehow HAS to run at least once. The part of my program is:

    printf("Enter number e: \n");
    scanf("%f", &e);

    do
    {

    printf("Enter number e: \n");
    scanf("%f", &e);
    }
    while(e<0.0001 || e>0.1);

    If I enter 0.01 for example, I get the message "Enter number e" and when I enter 0.01 again, the program goes out of the loop. Shouldn't it skip the do part and continue without the loop after the first input?
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,614
    Rep Power
    1945
    Do-while loop runs at lease one time, as the condition is place at the end of the block.

    If you want to validate before entering/starting a loop, you should use the "normal" while-loop:
    Semi-pseudo-code example:
    Code:
    printf("Enter number e: \n");
    scanf("%f", &e);
    while(e<0.0001 || e>0.1)[
       // do something 
    }
    From what you say:
    Code:
    The problem is that it somehow HAS to run at least once
    It sounds like you need the do-while-loop, but then you only have to ask for user input once.
    Code:
    do
    {
    
    printf("Enter number e: \n");
    scanf("%f", &e);
    }
    while(e<0.0001 || e>0.1);

IMN logo majestic logo threadwatch logo seochat tools logo