Reputation: 85
how do I detect if a user input int is between 2 numbers?
I've tried doing this:
int x=3;
printf("Enter the size of the triangle: ");
scanf("%d", &size);
odd=size%2;
for(x=3;x<21;x++)
{
if(x==size&&odd==1)
{
break;
}
else
{
printf("The size must be an odd number and be between\n3 and 21, inclusive, please try again\n\n");
printf("Enter the size of the triangle: ");
scanf("%d",&size);
odd=size%2;
x=3;
}
}
But the only input I can use is 3.
Upvotes: 0
Views: 438
Reputation: 881553
If your need is to continuously ask the user for a number until they enter one that's:
you can use something like:
printf ("Enter the size of the triangle: ");
scanf ("%d", &size);
while ((x < 3) || (x > 21) || (x % 2 == 0)) {
printf ("The size must be an odd number and be between\n"
"3 and 21, inclusive, please try again.\n\n");
printf ("Enter the size of the triangle: ");
scanf ("%d", &size);
}
This is probably the simplest form. It gets the number then enters the while
loop until it's valid.
You could refactor the printf/scanf
pair into a separate function but that's probably not so important in a small snippet like this.
Upvotes: 1
Reputation: 39950
You already have all the bits of the solution in the code:
if (size >= 3 && size <= 21) {
// size is between 3 and 21 inclusive
} else {
// size is less than 3 or more than 21
}
If you also want to ensure it's odd, you can add the condition:
if ((size >= 3) && (size <= 21) && (size % 2 == 1)) {
// size is between 3 and 21 inclusive, and odd
} else {
// size is less than 3 or more than 21 or even
}
Upvotes: 3
Reputation: 19760
printf("Enter the size of the triangle");
scanf("%d", &size);
if (3 <= size && size <= 21 && size % 2) {
// size is between 3 and 21 (inclusive) and odd
}
Upvotes: 0