Section 9.13 Summary
Various ways to use branching statements in C:
if (condition){ statement; }
if (condition){ statement1; statement2; ... }
if (condition){ statement(s); } else { statement(s); }
if (condition){ statement(s); } else if (other condition){ statement(s); } else if (yet another condition){ statements(s); } else { statement(s); }
- There can be as many
if-else
cases as you would like. - The final
else
statement can be omitted if that makes sense.
Several conditions can be combined with logic operators:
&&
is the logical AND||
is the logical OR!
is the logical NOT- DeMorgan 1:
!(A && B) == (!A) || (!B)
- DeMorgan 2:
!(A || B) == (!A) && (!B)
Relational and equality operators are:
<
less than>
greater than<=
less than or equal>=
greater than or equal==
equal!=
not equal
A few extra topics when it comes to branching and logic expressions in coding:
- Operator precedence in logic expressions
- Using a "flag" variable to represent true/false
- Translating logical expressions from English to C
- Negating logical expressions