Sunteți pe pagina 1din 7

Objectives

Learn about selection or how to make decisions:

ƒLogical data and operators.


ƒThe if and if … else selection statements.
Rossitza S. Marinova
Concordia University College of Alberta ƒConditional expressions.
ƒThe sw itch statement.

Introduction Structured Programming


‹ Before writing a program: ‹ Programs, written in 1950s and 1960s were a maze of complexity
ƒHave a thorough understanding of the problem known as “spaghetti code”.
ƒCarefully plan an approach for solving it ‹ In 1968, Edsger Dijkstra proposed that any program could be

‹ While writing a program: written with only three constructs or types of instructions:
ƒSequences: Built into C. Programs executed sequentially by default
ƒKnow what “building blocks” are available
(sequential operations)
ƒUse good programming principles
ƒSelection: C has three types: if , if… else , and sw itch
‹ Computing problems (conditional operations)
ƒAll can be solved by executing a series of actions in a specific order ƒRepetition: C has three types: w hile , do… w hile and for
‹ Algorithm: procedure in terms of (iterative operations)
ƒActions to be executed ‹ Today, virtually all programming languages offer structured
ƒThe order in which these actions are to be executed programming capabilities.
‹ Program control ‹ The second of the structured programming constructs is

ƒSpecify order in which statements are to be executed selection. Selection allows you to choose between two or more
alternatives: It allows you to make decisions.
3 4
Two-Way Selection if… else Statement
‹ The basic decision statement in the computer is the two-way selection. ‹ C implements two-way selection with the if…else statement.
‹ The decision is described to the computer as a conditional statement that ‹ An if…else statement is a composite statement used to make a
can be answered either true or false. decision between two alternatives.
ƒIf the answer is true, one or more
action statements are executed.
ƒIf the answer is false, then a
different action or a set of actions
is executed.
ƒRegardless of which set of action
is executed, the program
continues with the next statement
after the selection
‹ Diamond symbol (decision symbol).

ƒIndicates decision is to be made


ƒContains an expression that can be true or false
ƒTest the condition, follow appropriate path
13 14

Syntactical Rules for if…else A Simple if…else Statement


1. The expression must be enclosed in parentheses. ‹ In these two examples, each action is a single statement.
2. No semicolon (;) is needed for an if…else statement. ‹ The semicolons belong to the arithmetic and printf statements,
3.statem ent1 and statem ent2 may have a semicolon as not the if…else.
required by their types.
4. The expression can have a side effect.
5. Both the true and the false statements can be any statement
(even another if…else statement) or can be a null statement.
6. Both statem ent1 and statem ent2 must be one and only
one statement. Remember, however, that multiple
statements can be combined into a compound statement if ( grade > = 50 )
through the use of braces. printf( "Passed\n");
7. We can swap the position of statem ent1 and else
statem ent2 if we use the complement of the original printf( "Failed\n");
expression.
15 16
Compound Statements in if…else Complemented if…else statements
The true and false statements can be exchanged by complementing
the expression. When we find that we need to complement an if…else
statement, all we have to do is to switch the true and false statements.
if ( grade > = 50 )
printf( "Passed\n");
else
printf( "Failed\n");

if ( !(grade > = 50) )


printf( "Failed\n");
A compound statement only A compound statement for else
for the true condition both conditions
printf( "Passed\n");
C example
Compound statements begin with an open brace and end with
a close brace.
17 18

Null else Statement A null if Statement


‹ Although there are always two possible action after a decision, To eliminate the true branch of an if…else statement, we can
sometimes we do not care about both of them. In this case, the false complement the expression and swap the two statement.
action is usually left out.
‹ If the false condition is not required – that is, if it is null – it can be

omitted. This omission can be shown as a null else statement (a null


statement consists of only a semicolon).
‹ The true statement
cannot be omitted.
It can be coded as a
null statement.
‹ Normally, we do
not use null
statement in the
true branch of an
if…else statement.

19 20
Two-way Selection Example Nested if Statements
/* ****************************************************************
** This program is provided to the professors and students **
** using "Com puter Science: A Structured Approach U sing C, **
‹ For the if…else, the statements may be any statement, including
** Second Edition." Allreprints in any form m ust cite this ** another if…else.
** copyright. **
** C opyright(c) 2001 by Brooks/Cole **Results: ‹ When if…else is included within an if…else, it is known as a nested if
** A division of Thom son Learning **
Please enter tw o
*****************************************************************/
integers: 3 5 statement.
3 <= 5
# include < stdio.h>
int m ain (void) { ‹ There is no limit
/*LocalD efi nitions */ to how many
int a; Results:
levels can be
int b; Please enter tw o integers: 5 3
5> 3 nested, but if
/*Statem ents */ there are more
printf("Please enter tw o integers: ");
scanf ("% d% d",& a,& b);
than three, they
Results:
can become
Please enter tw o integers: 5 5
if (a < = b)
5 <= 5
difficult to read.
printf("% d < = % d\n",a,b);
else
printf("% d > % d\n",a,b);
return 0;
} /* m ain */
21 22

Nested (cascaded) if Statements Dangling else Problem


/* ****************************************************************
** This program is provided to the professors and students **
** using "Com puter Science: A Structured Approach U sing C, **
‹ Dangling else is created when there is no matching else for every if.
‹ C’s solution to this problem is a simple rule:
** Second Edition." Allreprints in any form m ust cite this **
** copyright. **
** C opyright(c) 2001 by Brooks/Cole
** A division of Thom son Learning
**
**
Always pair an else to the most recent unpaired if in the
*****************************************************************/ current block.
# include < stdio.h>
Results:
int m ain (void) { ‹ This rule may
Please enter tw o integers: 5 5
/*LocalD efi n itions */
5 == 5 result in some if
int a;
int b; statement being
left unpaired.
/*Statem ents */
printf("Please enter tw o integers: "); ‹ You must take
scanf ("% d% d",& a, & b);
if (a < = b) Results: care to ensure
if (a < b) Please enter tw o integers: 3 5 that the resulting
printf("% d < % d\n",a,b); 3< 5
else code is what you
printf("% d = = % d\n", a, b); need.
else
printf("% d > % d\n",a,b);
return 0;
} /* m ain */
23 24
Dangling else Solution Conditional Expressions
‹ A solution to the dangling else problem is a compound statement. ‹ C provides a convenient alternative to the traditional if…else for two-way
‹ You enclose the true actions in braces to make the second if a
selection – the ternary conditional expression.
compound statement. ‹ The conditional expression has three operands and two operators.

‹ Since the expression ? expression1 : expression2


closing brace ‹ If the expression is
completes the true, then the value of
body of the the conditional
compound expression is the value
statement, the of expression1
else is ‹ Otherwise, the value

automatically of the conditional


paired with expression is the value
the correct if. of expression2
‹ Example: grade > = 50 ? printf( “Passed\n” ) :printf( “Failed\n” );
‹ Although you can nest conditional expressions, it is not recommended.
25 26

Multiway Selection The switch Statement


‹ The switch expression contains the condition that is evaluated.
‹ Multiway selection chooses among several alternatives.
‹ For every possible value that can result from the condition, a
‹ C has two different ways to implement multiway selection. separate case constant is defined.
ƒThe first is by using the switch statement ‹ Associated with each possible case is zero or more statements.
The switch statement can be used only when the selection
condition reduces to an integral expression.
ƒThe second is a programming technique known as the else-if
switch decision logic
that provides a convenient style to nest if statements.
‹ Switch is a composite statement used to make decision
between many alternatives.
ƒThe selection condition must be one of the C integral types.
ƒThe most common used expression is a unary expression in the
form of an integral identifier.

27 28
The switch Statement The switch Statement
‹ The format must include at least one case ‹ As a result of the switch evaluation,
statement. one and only one of the cases will be
‹ Each case expression is associated with a enabled (the switch closed), so that
constant. The keyword case together with there will be a path for the program
its constant are known as a case-labeled to follow. (If none of the switches is
statement. closed, then the statement is skipped
‹ The label is a syntactical identifier that C
and the program continues with the
uses to determine which statement is the next statement after the switch.
starting point in the switch statement. ‹ What happens once the program flow

‹ The case is followed by a colon (:) and then


enters a case statement. When the
the statement with which it is associated. statements associated with one case
have been executed, the program
‹ Each case may have zero or more
flow continues with the statements
statements. for the next case. (Or, once the
‹ Default is executed whenever none of the programs enters trough a closed
other case values matches the value in the switch, it executes the code for all of
switch expression. the following cases until the end.
29 30

The switch Statement switch and break Statements


/* Sw itch dem onstration */ The break statement causes the program to jump out of
sw itch (printFlag) the switch statement–that is, to go to the closing brace and
{ continue with the code that follows the switch.
case 1: printf(“This is case 1\n");

case 2: printf(“This is case 2\n");

default: printf(“This is default\n");


} /* sw itch */

31 32
Multivalued case Statements Summary of switch Statement Rules
/* M ultiple cases for one set of statem ents dem onstration */ 1. The control expression that follows the keyword switch must be
sw itch (printFlag) an integral type.
{
case 1: 2. The expression followed by each case label must be a constant
case 3: printf(“H i,\n"); expression. A constant expression is an expression that is
printf(“this is an odd case!\n"); evaluated at compilation time, not run time.
break;
case 2: 3. No two case labels can have the same value.
case 4: printf(“H i,\n");
4. But two case labels can be associated with the same statements.
printf(“this is an even case!\n");
break; 5. The default label is not required. If the value of the expression
default:printf(“This isn’t a num ber betw een 2 and 4!\n"); does not match with any label, the control transfers outside the
printf(“Bye!\n");
switch statement.
break;
} /* sw itch */ 6. The switch statement can include at most one default label. The
default label may be coded anywhere, but it is traditionally
coded last.

33 34

Tips and Common Programming Errors Summary


‹ Encapsulate the statements inside braces if you have more than one ‹ The switch statement is used to
statement after if or else in an if…else statement. make a decision between many
‹ Do not use the equal operator with a floating point number. Floating point alternatives when the different
numbers are seldom equal to a required value. When you need to test for conditions can be expressed as
equality, such as a = = b, use integral values.
if (fabs (a - b) < 0.000001) ‹ Selection in C is done using two ‹ A case-labeled statement is used

‹ Do not forget to use a break statement when the cases in a switch statement statements: if...else and switch. for selection in a switch statement.
are exclusive. ‹ The if...else construct is used for ‹ A default-labeled statement is used

‹ The most common C error is using the assignment operator (=) in place of selection between two alternatives. as the last statement in a switch
the equal operator (= =). ‹ You can swap the statements in the
statement, to be executed when
true and false branches if you use the none of the case alternatives match
‹ It is a compile error to use a variable rather than an integral constant as the
complement of an expression in an the tested value.
value in a case label.
if...else statement. ‹ Indenting the controlled
‹ It is a compile error to use the same constant in two case labels.
‹ Multiway selection can be
statements in C is good style that
‹ It is generally a logic error to use side effects in the second operand in a enhances the readability of a
logical binary expression, such as (a+ + & & --b) , because the second accomplished using either the switch
statement or an else-if format. program.
operand may not be evaluated.
35 36

S-ar putea să vă placă și