Tuesday, September 21, 2010

Selection Statements if and switch

C/C++ supports two types of selection statements: if and switch. In addition, the ?
operator is an alternative to if in certain circumstances.
if
The general form of the if statement is
if (expression) statement;
else statement;
where a statement may consist of a single statement, a block of statements, or nothing
(in the case of empty statements). The else clause is optional.
If expression evaluates to true (anything other than 0), the statement or block that
forms the target of if is executed; otherwise, the statement or block that is the target of
else will be executed, if it exists. Remember, only the code associated with if or the
code associated with else executes, never both.
In C, the conditional statement controlling if must produce a scalar result. A scalar
is either an integer, character, pointer, or floating-point type. In C++, it may also be of
type bool. It is rare to use a floating-point number to control a conditional statement
because this slows execution time considerably. (It takes several instructions to perform
a floating-point operation. It takes relatively few instructions to perform an integer or
character operation.)
The following program contains an example of if. The program plays a very simple
version of the "guess the magic number" game. It prints the message ** Right ** when
the player guesses the magic number. It generates the magic number using the
standard random number generator rand() , which returns an arbitrary number
between 0 and RAND_MAX (which defines an integer value that is 32,767 or larger).
rand() requires the header file stdlib.h. (A C++ program may also use the new-style
header <cstdlib>.)
/* Magic number program #1. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic) printf("** Right **");
return 0;
}
Taking the magic number program further, the next version illustrates the use of
the else statement to print a message in response to the wrong number.
/* Magic number program #2. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic) printf("** Right **");
else printf("Wrong");
return 0;
}

Nested ifs
A nested if is an if that is the target of another if or else. Nested ifs are very common
in programming. In a nested if, an else statement always refers to the nearest if
statement that is within the same block as the else and that is not already associated
with an else. For example,

if(i)
{
if(j) statement 1;
if(k) statement 2; /* this if */
else statement 3; /* is associated with this else */
}
else statement 4; /* associated with if(i) */
As noted, the final else is not associated with if(j) because it is not in the same block.
Rather, the final else is associated with if(i). Also, the inner else is associated with if(k),
which is the nearest if.
Standard C specifies that at least 15 levels of nesting must be supported. In practice,
most compilers allow substantially more. More importantly, Standard C++ suggests
that at least 256 levels of nested ifs be allowed in a C++ program. However, nesting
beyond a few levels is seldom necessary, and excessive nesting can quickly confuse the
meaning of an algorithm.
You can use a nested if to further improve the magic number program by
providing the player with feedback about a wrong guess.
/* Magic number program #3. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* get a random number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if (guess == magic) {
printf("** Right **");
printf(" %d is the magic number\n", magic);
}
else {
printf("Wrong, ");
if(guess > magic) printf("too high\n");
else printf("too low\n");
}
return 0;
}
The if-else-if Ladder
A common programming construct is the if-else-if ladder, sometimes called the if-else-if
staircase because of its appearance. Its general form is
if (expression) statement;
else
if (expression) statement;
else
if (expression) statement;
..
.
else statement;
The conditions are evaluated from the top downward. As soon as a true condition is
found, the statement associated with it is executed and the rest of the ladder is
bypassed. If none of the conditions are true, the final else is executed. That is, if all
other conditional tests fail, the last else statement is performed. If the final else is not
present, no action takes place if all other conditions are false.
Although the indentation of the preceding if-else-if ladder is technically correct, it
can lead to overly deep indentation. For this reason, the if-else-if ladder is generally
indented like this:
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
.
..
else
statement;
Using an if-else-if ladder, the magic number program becomes
/* Magic number program #4. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic) {
printf("** Right ** ");
printf("%d is the magic number", magic);
}
else if(guess > magic)
printf("Wrong, too high");
else printf("Wrong, too low");
return 0;
}
The ? Alternative
You can use the ? operator to replace if-else statements of the general form:
if(condition) expression;
else expression;
However, the target of both if and else must be a single expression—not another
statement.
The ? is called a ternary operator because it requires three operands. It takes the
general form
Exp1 ? Exp2 : Exp3
where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true,
Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression. For example,
consider x = 10;
y = x>9 ? 100 : 200;
In this example, y is assigned the value 100. If x had been less than 9, y would have
received the value 200. The same code written with the if-else statement would be
x = 10;
if(x>9) y = 100;
else y = 200;
The following program uses the ? operator to square an integer value entered by
the user. However, this program preserves the sign (10 squared is 100 and −10 squared
is −100).
#include <stdio.h>
int main(void)
{
int isqrd, i;
printf("Enter a number: ");
scanf("%d", &i);
isqrd = i>0 ? i*i : -(i*i);
printf("%d squared is %d", i, isqrd);
return 0;
}
The use of the ? operator to replace if-else statements is not restricted to
assignments only. Remember, all functions (except those declared as void) may return
a value. Thus, you can use one or more function calls in a ? expression. When the
function's name is encountered, the function is executed so that its return value may be
determined. Therefore, you can execute one or more function calls using the ? operator
by placing the calls in the expressions that form the ?'s operands. Here is an example.
#include <stdio.h>
int f1(int n);
int f2(void);
int main(void)
{
int t;
printf("Enter a number: ");
scanf("%d", &t);
/* print proper message */
t ? f1(t) + f2() : printf("zero entered.\n");
return 0;
}
int f1(int n)
{
printf("%d ", n);
return 0;
}
int f2(void)
{
printf("entered.\n");
return 0;
}
Entering a 0 in this example calls the printf() function and displays the message zero
entered. If you enter any other number, both f1() and f2() execute. Note that the value
of the ? expression is discarded in this example. You don't need to assign it to anything.
A word of warning: Some C++ compilers rearrange the order of evaluation of an
expression in an attempt to optimize the object code. This could cause functions that
form the operands of the ? operator to execute in an unintended sequence.
Using the ? operator, you can rewrite the magic number program yet again.
/* Magic number program #5. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic;
int guess;
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic) {
printf("** Right ** ");
printf("%d is the magic number", magic);
}
else
guess > magic ? printf("High") : printf("Low");
return 0;
}
Here, the ? operator displays the proper message based on the outcome of the test
guess > magic.

No comments:

Post a Comment