The simplest calculating machines (see calculator) could only execute a series of calculations in an unalter-able sequence. Part of the transition from calculator to full computer is the ability to choose different paths of execu-tion according to particular values—in some sense, to make decisions.
Branching statements (also called decision statements or selection statements) give programs the ability to choose one or more different paths of execution depending on the results of a logical test. The general form for a branching statement in most programming languages is
if (Boolean expression)
statement
else statement
For example, a blackjack game written in C might have a statement that reads:
if ((Card_Count + Value(This_Card)) > 21) printf (“You’re busted!”);
Here the Boolean expression in parenthesis following the if keyword is evaluated. If it is true, then the following state-ment (beginning with printf) is executed. (The Boolean expression can be any combination of expressions, function calls, or even assignment statements, as long as they evalu-ate to true or false—see also boolean operators.)
The else clause allows the specification of an alternative statement to be executed if the Boolean expression is not true. The preceding example could be expanded to:
if (Card_Count + Value (This_Card) > 21) printf (“You’re busted!”);
else
printf(“Do you want another card?”);
In most languages if statements can be nested so that a second if statement is executed only if the first one is true. For example:
if (Turn > Max_Turns)
{
if (Winner() ) PrintScore();
}
Here the first if test determines whether the maximum number of turns in the game has been exceeded. If it has, the second if statement is executed, and the Winner() func-tion is called to determine whether there is a winner. If there is a winner, the PrintScore() function is called. This example also illustrates the general rule in most languages that wherever a single statement can be used a block of statements can also be used. (The block is delimited by braces in the C family of languages, while Pascal uses Begin . . . End.)
The switch or case statement found in many languages is a variant of the if statement that allows for easy testing of several possible values of a condition. One could write:
if (Category = = “A”) AStuff();
else if (Category = = “B”) BStuff();
else if (Category = = “C”) CStuff();
else
printf “(None of the above\n”);
However, C, Pascal, and many other languages provide a more convenient multiway branching statement (called switch in C and case in Pascal). Using a switch statement, the preceding test can be rewritten in C as:
switch (Category) { case “A”:
AStuff();
break; case “B”:
BStuff();
break; case “C”
CStuff();
break;
default:
printf (“None of the above\n”);
}
(Here the break statements are needed to prevent execution from continuing on through the other alternatives when only one branch should be followed.)
No comments:
Post a Comment