I am new to programming. I am doing my homework and the codes work so I won't post my whole codes out. I just wonder if it is possible to add "&&" and "||" in the same condition - my condition is a must be equal to 16 and b equal to any number from 5-9. Any suggestions? e.g.
if ( a == 16)
{
if (b == 5 || b == 6 || b == 7 || b == 8 || b == 9 )
{
printf("you pass\n");
}
}
Thanks a lot :)
Yes; just do it, and use parentheses to make it unambiguous:
if ((a == 16) && (b == 5 || b == 6 || b == 7 || b == 8 || b == 9))
or, if b
is an integer:
if (a == 16 && b >= 5 && b <= 9)
Ideally, though, you would describe the meaning of these chains of conditions using names, then come up with a much more expressive bit of code:
const bool theFooIsOkay = (a == 16);
const bool theBarIsGood = (b >= 5 && b <= 9);
if (theFooIsOkay && theBarIsGood)
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With