0

The request is that the user must input numbers until they fit within the numbers 1 and 13

for (N=0; N>13 && N<1; scanf("%d",&N))
{
    printf("fits");
}

This doesn't work, do I have to rephrase it somehow?

nyetrying
  • 21
  • 2
  • How does it not work? What are the undesired symptoms? Please provide a [mre] to demonstrate them. – Yunnosch Jun 27 '22 at 05:10
  • I think this is the same problem as in https://stackoverflow.com/questions/69458480/how-to-compare-char-array-with-char-in-c-language/69458744 but probably not obviously enough to be considered a duplicate. – Yunnosch Jun 27 '22 at 05:16
  • Not checking the return value from `scanf` always leads to undefined behaviour. This can be seen as a case of [de Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws). – Neil Jun 27 '22 at 05:55
  • Please clarify "within 1 and 13 "; including 1 and 13 as good, or exclusing them as unwanted. – Yunnosch Jun 27 '22 at 08:14

2 Answers2

2

Your programmed condition N>13 && N<1 can never be true. So your loop body and the scanf("%d",&N) is never executed.

You do not want to "loop while the number is bigger than 13 AND lower than 1": you probably want to "loop while the number bigger than 13 OR lower than 1".

So N > 13 || N < 1.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 1
    You will probably find out, that you also want to make a check on the return value of scanf(), but that is beyond the scope of your question. – Yunnosch Jun 27 '22 at 05:27
-1
  • The problem with your code is that N > 13 && N < 1 will always be false.

A number can never be greater than 13 and less than 1 at the same time

  • You have to use || operator for the comparison like N > 13 || N < 1, Also N = 0 is redundant in your code.
  • And also you have to move the print statement outside the loop, otherwise, it will print fits every time it is not in the range.
int main()
{
    int input;
    int flag = scanf("%d", &input) == 0 ? 1 : 0;
    while (input < 1 || input > 13)
    {
        if (flag)
        {
            while (getchar()!='\n');
        }
        int flag = scanf("%d", &input) == 0 ? 1 : 0;
    }
    printf("fits");
    return 0;
}

while (getchar()!='\n') is used to clean the stdin.

when a user enters a non-numeric character scanf returns 0, So to prevent unexpected behavior you've to clean stdin first before calling another scanf statement.

Sidharth Mudgil
  • 1,293
  • 8
  • 25
  • You need to check that `scanf()` does not report zero because some non-numeric character was entered. Also, `N` is not initialized on the first iteration. – Jonathan Leffler Jun 28 '22 at 05:45