In this section, you will learn about basic C++ control structures. In order to understand them, you must first know your truth tables. Memorize these, know them like the back of your hand, as they are very, very important. These determine how things evaluate. And here they are.
AND truth table:
A B A and B True True True True False False False True False False False False
OR truth table:
A B A or B True True True True False True False True True False False False
As an example, assume these values:
P = True Q = True X = False Y = False
P (True) and Q (True) evaluates to True P (True) and X (False) evaluates to False P (True) or X (False) evaluates to True X (False) or Y (False) evaluates to False
By themselves, these are pretty easy. But when you begin to combine them, things get complicated. There are orders of operation for these as well. First are parentheses, then AND evaluations, and lastly OR evaluations, all in left to right order.
Using the same values given above:
P and Q and X
First P and Q, which evaluates to True
Then evaluate that answer, True, with X: True and X (False), evaluates to False
P and Q or X
First evaluate P and Q, which evaluates to True
Then evaluate that answer, True, with X: True or X (False) evaluates to True
P and ( Q or X )
Here, evaluate the parentheses first, Q (True) or X (False), which evaluates to True
Then the and, P (True) and True evaluates to True.
You can also add a "not" to a value, thereby changing it to its inverse:
notP evaluates to False
P and notX evaluates to True
Now, try these one out yourself on some scratch paper:
a) ( P or X ) and ( P and Q )
b) P or notX and Q or Y
c) P and not( Q and Y )
You should have evaluated all True answers. Be sure you try these for yourself, to practice and gain an understanding of them, this is a very valuable prelude to the following lessons.
In C++, these AND and OR statements look like this: && for AND, || for OR. The Pipe ( | ) character is located on most keyboards as the shift element of the \ key.
Get used to this:
P and Q would be P && Q
X or Y would be X || Y
And even closer to how you would think about it in C++, imagine each with parentheses around them:
(P) && (Q)
(X) || (Y)
Because you will be evaluating statements as true or false from within the parentheses. Think of it this way:
(this is true) && (this is true) would evaluate True
(this is false) || (this is false) would evaluate False
If you feel comfortable with this, let's move on to your first control structure, the if statement.