Reputation: 11
if (num1 == (1,2,3,4,5,6,7,8,9)){
*some command*
}
does this sequence work, if not can you guide me masters. I'm a beginner
Upvotes: 0
Views: 99
Reputation: 21532
If the numbers you're testing for are in a continuous range, you can bound the value with greater than and less than (or equals):
For example, if you're testing if an int
n
is one of 1, 2, 3, 4, 5, 6, 7, 8, 9, you can do this:
if(n >= 1 && n <= 9)
{
// Code
}
If, however, the numbers are not a continuous range you have no choice but to explicitly test every value. So, if you were checking if n
was one of 13, 57, -3, 11, -66, 100, you could have to write it out completely (or use a switch
statement or lookup table):
if(13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n)
{
// Code
}
Alternatively (only for integral types):
switch (n)
{
case 13:
case 57:
case -3:
case 11:
case -66:
case 100:
// Code
break;
}
You may want to write a helper method in the latter case to make it more clear what you're testing for. e.g.:
if(IsAcceptableValueForTask(n))
Where IsAcceptableValueForTask
returns an int
representing the truth (1
|0
) of 13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n
Upvotes: 2
Reputation: 1132
You can use
if (num1 == 1 || num1 == 2 || num1 == 3 || num1 == 4 || num1 == 5 || num1 == 6 || num1 == 7 || num1 == 8 || num1 == 9 ){
//code
}
If you want to check between a range of numbers you can use
if(num1 >= 1 && num1 <= 9) {
//code
}
You can also use switch
statement for more convenience if the numbers are random and there are many conditions
Upvotes: 1
Reputation: 5331
Try this:
if(num1 >= 1 && num1 <= 9) {
// Some code
}
&& operator
will make sure num1
should be between 1 to 9 including it (i.e. 1, 9). It will execute some code only if both the conditions are true
.
Upvotes: 2