-6

I want the user to be able to immediately re-enter another value if the value originally entered is less than 0 or more than 23. Currently, my code outputs "please re-enter a value less than 24" and stops. It then has to be run again before the user can re-input another value.

{
    printf ("What is the height of the half-pyramids?\n");
        int height = get_int();
        if (height>23)
        {
            printf("please re-enter a value less than 24\n");
        }
        else if (height<0)
        {
            printf("please re-enter a value more than 0\n");
        }
        else
        {
            printf("%i", height);
    }

}

2 Answers2

2

Use a loop.

while(1) {
    printf ("What is the height of the half-pyramids?\n");
    int height = get_int();
    if (height>23)
    {
        printf("please re-enter a value less than 24\n");
    }
    else if (height<0)
    {
        printf("please re-enter a value more than 0\n");
    }
    else
    {
        printf("%d\n", height);
        break; // stop stop looping
}

BTW, it's more idiomatic to use %d to print integers, not %i. See What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

You could use a do-while loop:

do {
    printf ("What is the height of the half-pyramids?\n");
    int height = get_int();
    if (height > 23) {
        printf("please re-enter a value less than 24\n");
    } else if (height <= 0) {
        printf("please re-enter a value more than 0\n");
    }
    else {
        printf("%i", height);
    }
} while (height <= 0 || height > 23);
Mureinik
  • 297,002
  • 52
  • 306
  • 350