Search code examples
cparametersintegerprompt

Prompting user for integer 2> and >9 in C


Really rookie question about C...

I want the user to enter a number between 2 and 9, and if they don't, the prompt repeats itself until an integer within my parameters is entered. I can get this to work with one parameter ie

  int between_2_and_8(string prompt)
{
    int n;
    do
    {
        n = get_int("%s", prompt);
    }
    while (n > 8);
    return n;
}

but not having luck putting 2 parameters in. Here is the snippet:

int between_2_and_8(string prompt)
{
    int n;
    do
    {
        n = get_int("%s", prompt);
    }
    while (n > 8);
    return n;

    while (n < 2);
    return n;

}

Solution

  • You can add two conditions to continue your do-while loop .

    Modify your code as below:

    int between_2_and_8(string prompt)
    {
        int n;
        do
        {
            n = get_int("%s", prompt);
        }
        while (n < 3  || n > 8); // continue looping till either n is less than 3 or greater than 8
        return n;
    }
    

    EDIT: Corrected conditions