0% found this document useful (0 votes)
4 views61 pages

Chapter 3-Selection Structures in C-PreClass

Chapter 3 of 'C How to Program' discusses selection statements in C, including the if, if...else, and switch statements. It explains the structure and flow of these statements, including nested if...else statements and the use of the conditional operator. Additionally, it covers assignment operators, increment and decrement operators, and common error types in programming.

Uploaded by

8gsbwvv62j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

Chapter 3-Selection Structures in C-PreClass

Chapter 3 of 'C How to Program' discusses selection statements in C, including the if, if...else, and switch statements. It explains the structure and flow of these statements, including nested if...else statements and the use of the conditional operator. Additionally, it covers assignment operators, increment and decrement operators, and common error types in programming.

Uploaded by

8gsbwvv62j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter 3

Structured Program
Development in C

C How to Program, 8/e

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights


1
reserved.
Selection Statements in C

• C provides three types of selection structures in the


form of statements.
– The if selection statement either selects (performs) an action if
a condition is true or skips the action if the condition is false.
– The if…else selection statement performs an action if a
condition is true and performs a different action if the
condition is false.
– The switch selection statement performs one of many
different actions depending on the value of an expression.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 2
Selection Statements in C

• The if statement is called a single-selection statement


because it selects or ignores a single action.

• The if…else statement is called a double-selection


statement because it selects between two different actions.

• The switch statement is called a multiple-selection


statement because it selects among many different actions.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 3


The if Selection Statement
• The flowchart of Fig. 3.2 illustrates the single-selection if statement.
• This flowchart contains what is perhaps the most important
flowcharting symbol—the diamond symbol, also called the
decision symbol, which indicates that a decision is to be made.
• The decision symbol contains an expression, such as a condition,
that can be either true or false.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 4


The if Selection Statement

• The decision symbol has two flowlines emerging from it.


• One indicates the direction to take when the expression in the
symbol is true and the other the direction to take when the
expression is false.
• Decisions can be based on conditions containing relational or
equality operators.
• In fact, a decision can be based on any expression
– if the expression evaluates to zero, it’s treated as false, and
– if it evaluates to nonzero, it’s treated as true.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 5
The if Selection Statement

...
if ( grade >= 60 ) {
printf( "Passed\n" );
} // end if
...

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 6


The if…else Selection Statement

• The if…else selection statement allows you to specify that different actions
are to be performed when the condition is true and when it’s false.
• For example, the pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
prints Passed if the student’s grade is greater than or equal to 60 and Failed if the student’s
grade is less than 60.
• In either case, after printing occurs, the next pseudocode statement in
sequence is “performed.” The body of the else is also indented.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 7


The if…else Selection Statement
• The preceding pseudocode If…else statement may be written in C as
if ( grade >= 60 ) {
printf( "Passed\n" );
} // end if
else {
printf( "Failed\n" );
} // end else
• The flowchart of Fig. 3.3 illustrates the flow of control in the if…
else statement.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 8


The if…else Selection Statement

...
int a = 15
int b = 10
if ( a = b ) {
printf( ”%d is equal to %d\n", a, b);
} // end if
else {
printf( ”%d is not equal to %d\n", a, b);
} // end else
...

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 9


Conditional Operator
• C provides the conditional operator (?:) which is closely related to the if…else statement.

Condition ? Action for “true” case : Action for ”false” case

• The conditional operator is C’s only ternary operator—it takes three operands.
• These together with the conditional operator form a conditional expression.
• The first operand is a condition.
• The second operand is the value for the entire conditional expression if the condition is
true and the third operand is the value for the entire conditional expression if the
condition is false.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 10


Conditional Operator

• For example, the puts statement

puts( grade >= 60 ? "Passed" : "Failed" );

contains as its second argument a conditional expression that


evaluates to the string "Passed" if the condition grade >= 60 is true
and to the string "Failed" if the condition is false.
• The puts statement performs in essentially the same way as the
preceding if…else statement.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 11


Conditional Operator
• The second and third operands in a conditional expression can also
be actions to be executed.
• For example, the conditional expression
grade >= 60 ? puts( "Passed" ) : puts( "Failed" );

is read, “If grade is greater than or equal to 60 then puts("Passed"),


otherwise puts( "Failed" ).” This, too, is comparable to the preceding
if…else statement.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 12


The if…else Selection Statement
Nested if...else Statements
• Nested if…else statements test for multiple cases by placing if…else statements inside if…else statements.
• For example, Consider the following pseudocode statement
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 13


The if…else Selection Statement
• This pseudocode may be written in C as

if ( grade >= 90 )
puts( "A" );
else
if ( grade >= 80 )
puts("B");
else
if ( grade >= 70 )
puts("C");
else
if ( grade >= 60 )
puts( "D" );
else
puts( "F" );

• If the variable grade is greater than or equal to 90, all four conditions will be true, but
only the puts statement after the first test will be executed.
• After that puts is executed, the else part of the “outer” if…else statement is skipped.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 14


The if…else Selection Statement

• You may prefer to write the preceding if statement as


if ( grade >= 90 )
puts( "A" );
else if ( grade >= 80 )
puts( "B" );
else if ( grade >= 70 )
puts( "C" );
else if ( grade >= 60 )
puts( "D" );
else
puts( "F" );

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 15


The if…else Selection Statement

• As far as the C compiler is concerned, both forms are equivalent.


• The latter form is popular because it avoids the deep indentation of the code to
the right.
• The if selection statement expects only one statement in its body—if you have
only one statement in the if’s body, you do not need the enclose it in braces.
• To include several statements in the body of an if, you must enclose the
set of statements in braces { and }.
• A set of statements contained within a pair of braces is called a compound
statement or a block.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 16


The if…else Selection Statement

• The following example includes a compound statement in


the else part of an if…else statement.
if ( grade >= 60 ) {
puts( "Passed. " );
} // end if
else {
puts( "Failed. " );
puts( "You must take this course again. " );
} // end else

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 17


The if…else Selection Statement

• In this case, if grade is less than 60, the program executes both puts
statements in the body of the else and prints
Failed.
You must take this course again.
• The braces surrounding the two statements in the else are important.
Without them, the statement
puts( "You must take this course again." );
would be outside the body of the else part of the if and would execute
regardless of whether the grade was less than 60.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 18


Error Types

• A syntax error is caught by the compiler.


• A logic error has its effect at execution time.
• A fatal logic error causes a program to fail and terminate prematurely.
• A nonfatal logic error allows a program to continue executing but to produce
incorrect results.
• Just as a compound statement can be placed anywhere a single statement can
be placed, it’s also possible to have no statement at all, i.e., the empty
statement.
– The empty statement is represented by placing a semicolon (;) where a statement
would normally be.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 19
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 20
reserved.
Self-Assessment Quiz

What is the output of the following


code?

a higher
int age = 21;
if ( age = 22 ) {
b lower printf( "higher\
n" );
} // end if
c It has compile-time error.
else {
printf( "lower\
d No output will generate. n" );
} // end else
Quiz Result

Sorry, your answer is wrong 

Try Again! int age = 21;


if ( age = 22 ) {
printf( "higher\
n" );
} // end if
else {
printf( "lower\
n" );
} // end else
Quiz Result: Excellent! 
What is the output of the following
code?
higher
int age = 21;
if ( age = 22 ) {
Continue printf( "higher\
n" );
} // end if
else {
printf( "lower\
n" );
} // end else
Assignment Operators
• C provides several assignment operators for abbreviating
assignment expressions.
• For example, the statement
• c = c + 3;
• can be abbreviated with the addition assignment operator += as
• c += 3;
• The += operator adds the value of the expression on the right of the
operator to the value of the variable on the left of the operator and
stores the result in the variable on the left of the operator.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 24


Assignment Operators (Cont.)

• Any statement of the form


• variable = variable operator expression;
• where operator is one of the binary operators +, -, *, / or % (or others
we’ll discuss in Chapter 10), can be written in the form
• variable operator= expression;
• Thus the assignment c += 3 adds 3 to c.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 25


Figure 3.11 shows the arithmetic assignment operators, sample
expressions using these operators and explanations.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 26


reserved.
Increment and Decrement Operators
• C also provides the unary increment operator, ++, and the unary decrement
operator, --, which are summarized in Fig. 3.12.
• If a variable c is to be incremented by 1, the increment operator ++ can be
used rather than the expressions c = c + 1 or c += 1.
• If increment or decrement operators are placed before a variable (i.e.,
prefixed), they’re referred to as the preincrement or predecrement
operators, respectively.
• If increment or decrement operators are placed after a variable (i.e.,
postfixed), they’re referred to as the postincrement or postdecrement
operators, respectively.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 27


Increment and Decrement Operators (Cont.)
• Preincrementing (predecrementing) a variable causes the variable to
be incremented (decremented) by 1, then the new value of the
variable is used in the expression in which it appears.
• Postincrementing (postdecrementing) the variable causes the
current value of the variable to be used in the expression in which it
appears, then the variable value is incremented (decremented) by 1.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 28


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 29
reserved.
Increment and Decrement Operators (Cont.)

• Figure 3.13 demonstrates the difference between the


preincrementing and the postincrementing versions of the ++
operator.
• Postincrementing the variable c causes it to be incremented after it’s
used in the printf statement.
• Preincrementing the variable c causes it to be incremented before
it’s used in the printf statement.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 30


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 31
reserved.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 32
reserved.
Increment and Decrement Operators (Cont.)
• The three assignment statements
• passes = passes + 1;
failures = failures + 1;
student = student + 1;
can be written more concisely with assignment operators as
• passes += 1;
failures += 1;
student += 1;
with preincrement operators as
• ++passes;
++failures;
++student;
or with postincrement operators as
• passes++;
failures++;
student++;

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 33


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 34
reserved.
Increment and Decrement Operators (Cont.)
• Figure 3.14 lists the precedence and associativity of the operators introduced to
this point.
• The operators are shown top to bottom in decreasing order of precedence.
• The second column indicates the associativity of the operators at each level of
precedence.
• Notice that the conditional operator (?:), the unary operators increment (++),
decrement (--), plus (+), minus (-) and casts, and the assignment operators =,
+=, -=, *=, /= and %= associate from right to left.
• The third column names the various groups of operators.
• All other operators in Fig. 3.14 associate from left to right.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 35


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights 36
reserved.
Self-Assessment Quiz

What is the output of the following


code?

a Yes
int age = 21;
if ( age++ == 22 ) {
b No printf( ”Yes\n" );
} // end if
else {
c It has compile-time error.
printf( ”No\n" );
} // end else
d No output will generate.
Quiz Result

Sorry, your answer is wrong 

Try Again! int age = 21;


if ( age++ == 22 ) {
printf( ”Yes\n" );
} // end if
else {
printf( ”No\n" );
} // end else
Quiz Result: Excellent! 
What is the output of the following
code?
No
int age = 21;
if ( age++ == 22 ) {
Continue printf( ”Yes\n" );
} // end if
else {
printf( ”No\n" );
} // end else
switch Multiple-Selection Statement
• Occasionally, an algorithm will contain a series of decisions in which a variable
or expression is tested separately for each of the constant integral values it
may assume, and different actions are taken.
• This is called multiple selection.
• C provides the switch multiple-selection statement to handle such decision
making.
• The switch statement consists of a series of case labels, an optional
default case and statements to execute for each case.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 40


41
42
Reading Character Input

• In the program, the user enters letter grades for a class.


• The getchar function (from <stdio.h>) reads one character from the
keyboard and returns as an int the character that the user entered.
• Characters are normally stored in variables of type char.
• However, an important feature of C is that characters can be stored in any
integer data type because they’re usually represented as one-byte integers in
the computer.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 43


Character <-> int

• Thus, we can treat a character as either an integer or a character,


depending on its use.
• For example, the statement
printf("The character (%c) has the value %d.\n", 'a', 'a');
• uses the conversion specifiers %c and %d to print the character a and its
integer value, respectively.
• The result is
The character (a) has the value 97.
• The integer 97 is the character’s numerical representation in the
computer.
©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 44
character <-> int
• Many computers today use the ASCII (American Standard Code for
Information Interchange) character set in which 97 represents the lowercase
letter 'a'.
• Characters can be read with scanf by using the conversion specifier %c.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 45


switch Multiple-Selection Statement (Cont.)
switch Statement Details
• Keyword switch is followed by the variable name grade in parentheses.
• This is called the controlling expression.
• The value of this expression is compared with each of the case labels.
• Assume the user has entered the letter C as a grade.
• C is automatically compared to each case in the switch.
• If a match occurs (case 'C':), the statements for that case are executed.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 46


switch Multiple-Selection Statement (Cont.)
• The break statement causes program control to continue with the first
statement after the switch statement.
• The break statement is used because the cases in a switch statement
would otherwise run together.
• If break is not used anywhere in a switch statement, then each time a match
occurs in the statement, the statements for all the remaining cases will be
executed—called fall through.
• If no match occurs, the default case is executed, and an error message is
printed.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 47


switch Multiple-Selection Statement (Cont.)
switch Statement Flowchart
• Each case can have one or more actions.
• The switch statement is different from all other control statements in that braces
are not required around multiple actions in a case of a switch.
• The general switch multiple-selection statement (using a break in each case) is
flowcharted in Fig. 4.8.
• The flowchart makes it clear that each break statement at the end of a case
causes control to immediately exit the switch statement.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 48


©2016 Pearson Education, Inc., Hoboken, NJ. All rights r 49
eserved.
©2016 Pearson Education, Inc., Hoboken, NJ. All rights r 50
eserved.
switch Multiple-Selection Statement (Cont.)

• Listing several case labels together (such as case 'D':


case 'd':) simply means that the same set of actions is to
occur for either of these cases.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 51


switch Multiple-Selection Statement (Cont.)

Constant Integral Expressions


• When using the switch statement, remember that each
individual case can test only a constant integral expression
—i.e., any combination of character constants and integer
constants that evaluates to a constant integer value.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 52


characters inside double quotes

• A character constant can be represented as the specific


character in single quotes, such as 'A'.
• Characters must be enclosed within single quotes to be
recognized as character constants—characters in double
quotes are recognized as strings.
• Integer constants are simply integer values.
• In our example, we have used character constants.
• Remember that characters are represented as small integer
values.
©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 53
Notes on Integral Types
• Portable languages like C must have flexible data type sizes.
• Different applications may need integers of different sizes.
• C provides several data types to represent integers.
• In addition to int and char, C provides types short int (which can be
abbreviated as short) and long int (which can be abbreviated as long),
as well as unsigned variations of all the integral types.
• The C standard specifies the minimum range of values for each integer type,
but the actual range may be greater and depends on the implementation.
• For short int the minimum range is –32767 to +32767.
• For most integer calculations, long int is sufficient.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 54


Notes on Integral Types

• The minimum range of values for long int is –


2147483647 to +2147483647.
• The range of values for an int greater than or equal to that
of a short int and less than or equal to that of a long
int.
• The data type signed char can be used to represent
integers in the range –127 to +127 or any of the characters
in the computer’s character set.

©2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 55


Self-Assessment Quiz

What is the output of the following


code?
float age = 21;
a 21 switch (age) {
case 21:
b 2122 printf(”21");
case 2:
c It has compile-time error. printf(”22");
break;
d 0 default:
printf("0");
}
Quiz Result

Sorry, your answer is wrong 

float age = 21;


Try Again! switch (age) {
case 21:
printf(”21");
case 2:
printf(”22");
break;
default:
printf("0");
}
Quiz Result: Excellent! 
What is the output of the following
code?
It has compile-time error. float age = 21;
switch (age) {
case 21:
Continue printf(”21");
case 2:
printf(”22");
break;
default:
printf("0");
}
Secure C Programming
Arithmetic Overflow
• Figure 2.5 presented an addition program which calculated the sum of two
int values with the statement

sum = integer1 + integer2; // assign total to sum

• Even this simple statement has a potential problem—adding the integers


could result in a value that’s too large to store in an int variable.
• This is known as arithmetic overflow and can cause undefined behavior,
possibly leaving a system open to attack.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 59


Secure C Programming (Cont.)
• The maximum and minimum values that can be stored in an int variable are
represented by the constants INT_MAX and INT_MIN, respectively, which are defined
in the header <limits.h>.
• You can see your platform’s values for these constants by opening the header
<limits.h> in a text editor.
• It’s considered a good practice to ensure that before you perform arithmetic
calculations, they will not overflow.
• The code for doing this is shown on the CERT website
www.securecoding.cert.org—just search for guideline “INT32-C.”
• The code uses the && (logical AND) and || (logical OR) operators, which are introduced
in the Chapter 4.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 60
Secure C Programming (Cont.)
Unsigned Integers
• In general, counters that should store only non-negative values should be
declared with unsigned before the integer type.
• Variables of unsigned types can represent values from 0 to approximately
twice the positive range of the corresponding signed integer types.
• You can determine your platform’s maximum unsigned int value with the
constant UINT_MAX from <limits.h>.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved. 61

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy