Until now, our code examples have been linear: control has flowed in one
direction from start to finish. In this chapter, we will examine ways to
enable code to make decisions and to choose among options. You will
learn how to program code that will function in situations similar to
the following:
If the user hits the jackpot, print a message to
say so: You've won!
If a bank balance is positive, then print C for "credit";
otherwise, print D for "debit".
If the user has typed in one of five choices, then do
something that corresponds to the choice, otherwise display an
error message.
In the first case there is a simple "do or don't" choice. In the
second case, there are two choices. The final case contains several
possibilities.
C offers four main ways of coding decisions like the ones above. They
are listed below.
if...
if (condition)
{
do something
}
if...else...
if (condition)
{
do something
}
else
{
do something else
}
...?...:...
(condition) ? do something : do something else;
switch
switch (condition)
{
case first case : do first thing
case second case : do second thing
case third case : do third thing
}