Home > Blockchain >  scanf until number fits in condition
scanf until number fits in condition

Time:06-27

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?

CodePudding user response:

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

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.

CodePudding user response:

  • 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 N;
    for (; N > 13 || N < 1; scanf("%d", &N)) {}
    printf("fits");
    return 0;
}

If I was given this problem, I would implement it like this.

int main()
{
    int input;
    scanf("%d", &input);
    while (input < 1 || input > 13)
    {
        scanf("%d", &input);
    }
    printf("fits");
    return 0;
}

CodePudding user response:

As Yunnosch answered that why your scanf will never be executed. As far as I have understood your problem, you want to take input from user until user enters number between 1 and 13. You can do this using while loop and break keyword. Run while loop with always true condition and take input in every iteration in loop body. After that check whether input satisfies conditions or not. If it satisfies the condition then use break; keyword to step out of the loop. Below is code for same

#include <stdio.h>

int main()
{
    int n = 0;
    while(1){
        scanf("%d", &n);
        if(n > 1 && n < 13){
            printf("fits");
            break;
        }
    }
    return 0;
}
  •  Tags:  
  • c
  • Related