hi everybody. Im really new to programming and had a real quick question thats been baffling me. The program I am working on involves giving different responses depending on the number range it falls into from the information inputed. like 0 to 80 = this response and 80 to 100 = this and so on. '
my question is simply to see if im on the right track by using if statements.
This is the truth table for || (boolean OR):
A || B = C
A B C
F F F
F T T
T F T
T T T
This is the truth table for && (boolean AND):
A && B = C
A B C
F F F
F T F
T F F
T T T
Thus, A || B is true if A and/or B are true (that is, at least one has to be true), and A && B is true if both A and B and true.
Now, suppose we have the number x, and we want to evaluate x<15 || x>5. Let's take a look at what happens when x is 0, 10, and 20:
x = 0
x < 15 = T
x > 5 = F
T || F = T
x = 10
x < 15 = T
x > 5 = T
T || T = T
x = 20
x < 15 = F
x > 5 = T
F || T = T
As you can see, no matter what the value of x is, the expression always evaluates to true. That's because ALL numbers are >5 and/or <15.
Let's repeat the procedure, but now we'll evaluate x<15 && x>5
x = 0
x < 15 = T
x > 5 = F
T && F = F
x = 10
x < 15 = T
x > 5 = T
T && T = T
x = 20
x < 15 = F
x > 5 = T
F && T = F
This time, the expression only evaluated to true when x was in the range [6;14], but to false when x had any other value.
You might notice that a value of 129 or 130 won't execute any of those paths. (130 is not > 130, and it's not < 129)
You don't need to have an upper and lower range for these. Just have a lower range. The 'else' takes care of the upper range automatically:
1 2 3 4 5 6 7
if(variable > 130)
cout << "variable is > 130";
elseif(variable > 100)
cout << "no need for <= 130 because the 'else' ensures the value is <= 130.\n"
<< "all we have to do is say > 100";
elseif(variable > 90)
cout << "same thing";