0

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;

}

2 Answers2

0

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

Vagish
  • 2,520
  • 19
  • 32
  • The opposite of a number _larger than_ 2 and _smaller than_ nine is: `n<=2 || n>=9`. Alternatively `n<3 || n>8`. Or if it was meant to include 2 and 9, then `n<2 || n>9`. – Lundin Jan 17 '19 at 07:45
-1

You will never enter the condition check while(n < 2) as either of the previous condition check or return n executes. ie. it loops around while (n > 8)when the condition is true or return ngets executed when the condition fails. So it will never execute the second condition check while (n < 2).

Try implementing a logical OR in a single while loop as below

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

}

Edit : Corrections made on condition check

Nerdy
  • 1,016
  • 2
  • 11
  • 27
  • The opposite of a number _larger than_ 2 and _smaller than_ nine is: `n<=2 || n>=9`. Alternatively `n<3 || n>8`. Or if it was meant to include 2 and 9, then `n<2 || n>9`. – Lundin Jan 17 '19 at 07:46