SlideShare a Scribd company logo
SC, Chen
Ch5 Selection Statement
Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch5 Selection Statement
• Operators
• Statements
Have encountered:
1. return statements
2. Expression statements
The three categories of most the remaining statements:
1. Selection statements
− If
− switch
2. Iteration statements
− while
− do
3. Jump statements
− break
− continue
− return
Other statements
1. Compound statements
2. NULL statement
return
statement
Ch 2.2
Expression
statement
Ch 4.5
Ch5 Selection Statement
5.1 Logical Expressions
5.2 The if Statement
5.3 The switch Statement
• Produce 0 (false) or 1 (true) when used in expressions
• Can be used to compare integers and floating-point numbers
Operands of mixed types allowed
• The precedence of the relational operators is lower than that of the
arithmetic operators
• Left-associative
5.1 Logical Expressions: Relational Operators
Symbol Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater then or equal to
5.1 Logical Expressions: Equality Operators
• “=“ character in C
1. The assignment operator: single = character (“=“)
2. The equality operator: two adjacent = characters (“==”)
• Produce 0 (false) or 1 (true) when used in expressions
• Left-associative
• The equality operators have lower precedence than the relational
operators
• The relational and equality operators return integer values
Tricky coding using this isn’t a good idea -> hard to read!
Symbol Meaning
== Equal to
!= Not equal to
i < j == j < k (i < j) == (j < k)
(i >= j) + (i == j) The value is 0, 1, or 2
5.1 Logical Expressions: Logical Operators
• Produce 0 (false) or 1 (true) when used in expressions
1. Treat any nonzero operand as true value
2. Treat any zero operand as false value
• “&&” and “||” short-circuit evaluation of their operands
These operators first evaluate the left operand.
Then the right operand is evaluated if the value of the expression cannot be deduced from the
value of the left operand alone.
Side effects may not always occur
The ! Operator has the same precedence as the unary plus and minus operators,
and is right associative
The precedence of && and || is lower than that of the relational and equality
operators, and is left associative
Symbol Meaning
! Logical negation
&& Logical and
|| Logical or
(i != 0) && (j / i > 0)
(i > 0) && ++j > 0
5.2 The if Statement
• The parentheses around the expression are mandatory
Part of if statement
• If the value of the expression is nonzero, which C interprets as true
The statement after the parentheses is executed
• Don’t confuse == (equality) with = (assignment)
If (i == 0)
If (i = 0) -> always false
• Often the expression in an if statement will test
1. Whether a variable falls within a range of values: 0 ≤ i < n
2. The opposite condition (outside the range) : i < 0 or i ≥ n
if ( expression ) statement
If (0 ≤ i && i < n)
If (i < 0 || i ≥ n)
Equality and Assignment Operators in if
• Using if (0 == i) to let compiler produce error message if use “=“ instead of
“==“
• Many compilers are capable of checking for suspect uses of the = operator
in if conditions
GCC compiler will perform check if the –Wparentheses option is used or if –Wall is
selected
GCC allows the programmer to suppress the warning in a particular case by
enclosing the if condition in a second set of parentheses
if ( (i == j) ) …
5.2 The if Statement: Compound Statements
• Putting braces around a group of statements can force the compiler
to treat it as a single statement
Each inner statement still ends will a semicolon
But the compound statement itself does not
• Compound statements are also common in loops and other places
where the syntax of C requires a single statement, but we want more
than one
if ( expression ) { statements }
if (line_num == MAX_LINES) {
line_num = 0;
page_num++;
}
{
line_num = 0;
page_num++;
}
Coding Style for Compound Statements
1. The K&R style
2. The Allman style
3. The Whitesmiths style
4. The GNU style
• According to The New Hacker’s Dictionary, there are 4 common styles of
indentation and brace placement
if (line_num == MAX_LINES) {
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
5.2 The if Statement: The else Clause
• If the expression in parentheses has the value 0, the statement that follows
the word else is executed
• Both inner statements end with a semicolon
• Coding Style
Align else with if
If only one short statement, statement can be put on the same line as the if and else
if statements can be nested to any depth
Adding braces to statements even when they’re not necessary
1. The program becomes easier to modify, because more statements can easily be added to any if
or else clause
2. It helps avoid errors that can result from forgetting to use braces when adding statements to
an if or else clause
if ( expression ) statement else statement
5.2 The if Statement: Cascaded if Statements
• Use cascaded if statements
to test a series of conditions
• C programmers align each
else with the original if
1. Avoid the problem of
excessive indentation when
the number of tests is large
2. Assure the reader that the
statement is nothing more
than a series of tests
if (n < 0)
printf (“n is less than 0n”)
else
if (n == 0)
printf (“n is equal to 0n”)
else
printf (“n is greater than 0n”)
if (n < 0)
printf (“n is less than 0n”)
else if (n == 0)
printf (“n is equal to 0n”)
else
printf (“n is greater than 0n”)
if ( expression )
statement
else if ( expression )
statement
…
else if ( expression )
statement
else
statement
5.2 Calculating a Broker’s Commission
• The minimum charge is $39
Transaction size Commission rate
Under $2,500 $30 + 1.7%
$2,500~$6,250 $56 + 0.66%
$6,250~$20,000 $76 + 0.34%
$20,000~$50,000 $100 +0.22%
$50,000~$500,000 $155 + 0.11%
Over$500,000 $255 + 0.09%
5.2 The if Statement: The “Dangling else”
Problem
1. C follows the rule that an else clause belongs to the nearest if
statement that hasn’t already been paired with an else
2. Using braces can clearly define the pair of if and else
if (y != 0)
if (x != 0)
result = x/y;
else
printf (“Error: y is equal to 0n”)
if (y != 0)
if (x != 0)
result = x/y;
else
printf (“Error: y is equal to 0n”)
if (y != 0) {
if (x != 0)
result = x/y;
}
else
printf (“Error: y is equal to 0n”)
1.
2.
5.2 The if Statement: Conditional Expressions (1/2)
• Conditional operators (? and : )
1. Must be used together
2. Allow an expression to produce one or two values depending on the value
of a condition
3. Require three operands: ternary operator
• expression 1, 2, 3 can be expressions of any type
• “if expression1 then expression2 else expression3”
1. expression1 is evaluated first
2. If value of expression1 isn’t zero, then expression2 is evaluated
3. If value of expression1 is zero, then expression3 is the value of the
conditional
expression1 ? expression2 : expression3
int i, j, k;
i = 1;
j = 2;
k = i > j ? i : j; /* k is now 2 */
k = (i >= 0 ? i : 0)+ j; /* k is now 3 */
• Conditional expressions tend to make programs shorter but harder to
understand
• A few places in which conditional expressions are tempting
1. return statement
2. printf
3. Certain kinds of macro definitions
if (i > j)
return i;
else
return j;
return i > j ? i : j;
if (i > j)
printf(“%dn”, i);
else
printf(“%dn”, j);
printf(“%dn”, i > j ? i : j);
Macro
definitions
Ch 14.3
5.2 The if Statement: Conditional Expressions (2/2)
Mixed-Types in Conditional Expressions
i > 0 ? i : f;
i is integer
f is floating-point number
The expression has type float
5.2 The if Statement: Boolean Value in C89
• The C language lacked a proper Boolean type for many years
There is no defined in the C89 standard
• Work around
1. Declare an int variable and then assign it either 0 or 1
Not contribute much to program readability
It is not obvious that flag is to be assigned only Boolean values
2. Define macros with names such as TRUE and FALSE
3. Carry 2. idea one step further, we can define a macro that can be used as a type
BOOL can take the place of int when declaring Boolean variables
4. Better way in later chapter by using type definition and enumerations
#define TRUE 1
#define FALSE 0
Test whether flag is True False
1st way if (flag == TRUE) … if (flag == FALSE) …
2nd way if (flag) … if (!flag) …
Better way
1. More concise
2. Still work correctly if flag has
a value other than 0 or 1
int flag
flag = 0;
…
flag = 1;
#define BOOL int;
BOOL flag;type definitions
Ch 7.5
enumerations
Ch 16.5
5.2 The if Statement: Boolean Values in C99
• C99 provides the _Bool type
An unsigned integer type
Can only be assigned 0 or 1
− Attempt to store a nonzero value into a _Bool variable will cause the variable to be
assigned 1
Is legal to
− Perform arithmetic on _Bool variables
− Print a _Bool variables
− Test _Bool variables in an if statement
•C99 also provides a new header <stdbool.h>
Provide a macro, bool, that stands for _Bool
Supply macros named true and false
#include <stdbool.h>
…
bool flag;
_Bool flag;
Unsigned
integer types
Ch 7.1
<stdbool.h>
header
Ch 21.5
_Bool in C99
• Why use _Bool instead of bool or Boolean?
Existing C programs might already define these names, causing older code not to
compile
The C89 standard specifics that names beginning with an underscore followed by
an uppercase letter are reserved for future use and should not be used by
programmers
5.3 The switch Statement (1/3)
• As an alternative to cascaded if statement, C provides the switch
statement
Easier to read than cascaded if statement
Often faster than if statements
if (grade == 4)
printf (“Excellent”);
else if (grade == 3)
printf (“Good”);
else if (grade == 2)
printf (“Average”);
else if (grade == 1)
printf (“Poor”);
else if (grade == 0)
printf (“Failed”);
else
printf (“Illegal grade”);
switch (grade) {
case 4:
printf (“Excellent”);
break;
case 3:
printf (“Good”);
break;
case 2:
printf (“Average”);
break;
case 1:
printf (“Poor”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
break
statement
Ch 6.4
Transfer control to the
statement following the
switch
If the value of grade doesn’t match
any of the choices listed, the
default case apply
default
1. Doesn’t need to come last
2. Not required
Control simply passes to the next
statement after the switch if
default is missing and the value of
the controlling expression doesn’t
match any of the case labels
5.3 The switch Statement (2/3)
switch ( expression ) {
case constant-expression : statements
…
case constant-expression : statements
default : statements
}
Controlling expression
1. Integer expression
2. Characters are treated as integers in C
3. Floating-point numbers and strings don’t qualify
Case labels
1. Each case begins with a label
2. constant-expression
1. Ordinary expression
2. Except it can’t contain
variables or function calls
3. An integer (characters
are also OK)
Statements
1. No braces are required
around the statements
2. The last statement in each
group is normally break
characters
Ch 7.3
5.3 The switch Statement (3/3)
• Duplicated case labels aren’t allowed
• The order of the cases doesn’t matter
• Only one constant expression may
follow the word case
Several case labels may precede the
same group of statements
• There is no way to write a case label
that specifies a range of values
switch (grade) {
case 4:
case 3:
case 2:
case 1:
printf (“Passing”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
switch (grade) {
case 4: case 3: case 2: case 1:
printf (“Passing”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
5.3 The switch Statement: The Role of the break
Statement
• switch statement is a form of “computed jump”
When the controlling expression is evaluated, control jumps to
the case label matching the value of the switch expression
A case label is just a position marker within the switch
When the last statement in the case has been executed, control
“falls through” to the first statement in the following case
− The case label for the next case is ignored
• Falling through from one case into the next is rare
It is good to point out any deliberate omission of break
• The last case in a switch statement is common to put one
break there
If cases should later be added
switch (grade) {
case 4: case 3: case 2: case 1:
num_passing++;
/*FALL THROUGH*/
case 0: total_grade++;
break;
}
switch (grade) {
case 4: printf (“Excellent”);
case 3: printf (“Good”);
case 2: printf (“Average”);
case 1: printf (“Poor”);
case 0: printf (“Failed”);
default: printf (“Illegal grade”);
}
5.3 Printing a Date in Legal Form
Other Form for switch Statement?
• The switch statement is b bit more general than described in this chapter
A switch statement can contain labels that aren’t preceded by the word case
switch (…) {
…
defualt: …
}
switch ( expression ) {
case constant-expression : statements
…
case constant-expression : statements
default : statements
}
switch ( expression ) statements
Also legal, because “default”
is an ordinary label
Coding Style of switch
1. Put the statements in each case
after the case label
Fine when the statements in each case
are short and there are relatively few of
them
2. Put the statements under the case
label, indenting the statements to
make the case label stand out
Better for large switch statements in
which the statements in each case are
complex and/or numerous
switch (grade) {
case 4: printf (“Excellent”);
break;
case 3: printf (“Good”);
break;
default: printf (“Failed”);
break;
}
switch (grade) {
case 4:
printf (“Excellent”);
break;
case 3:
printf (“Good”);
break;
default:
printf (“Failed”);
break;
}
• There are at least two common methods
switch (grade) {
case 4: printf (“Excellent”); break;
case 3: printf (“Good”); break;
default: printf (“Failed”); break;
}
Ad

More Related Content

What's hot (20)

Electrostatics 2
Electrostatics 2Electrostatics 2
Electrostatics 2
Shwetha Inspiring
 
Static Electricity
Static ElectricityStatic Electricity
Static Electricity
OhMiss
 
Exp SPA - Chp 16 Static Electricity
Exp SPA - Chp 16 Static ElectricityExp SPA - Chp 16 Static Electricity
Exp SPA - Chp 16 Static Electricity
harrywwh
 
1.1 electric charge
1.1 electric charge1.1 electric charge
1.1 electric charge
sitizalina96
 
Electricity
ElectricityElectricity
Electricity
Ed Stermer
 
4 current and resistance
4 current  and  resistance4 current  and  resistance
4 current and resistance
Ruben Conde
 
Electric Charge
Electric ChargeElectric Charge
Electric Charge
D MacCarthy
 
ELECTROSTATICS
ELECTROSTATICSELECTROSTATICS
ELECTROSTATICS
KANNAN
 
Solids, Conductors, Insulators & Semiconductors
 Solids, Conductors, Insulators & Semiconductors Solids, Conductors, Insulators & Semiconductors
Solids, Conductors, Insulators & Semiconductors
KamalKhan822
 
Photoelectric effect ppt
Photoelectric effect pptPhotoelectric effect ppt
Photoelectric effect ppt
Santosh Jadhav
 
Electricity and magnetism
Electricity and magnetismElectricity and magnetism
Electricity and magnetism
Rodtips
 
Electrostatics
ElectrostaticsElectrostatics
Electrostatics
kgyaninstitute
 
kirchoff's rules
kirchoff's ruleskirchoff's rules
kirchoff's rules
RG Luis Vincent Gonzaga
 
7.4 electromotive force and internal resistance
7.4 electromotive force and internal resistance7.4 electromotive force and internal resistance
7.4 electromotive force and internal resistance
Adlishah Risal Bili
 
Ohms Law
Ohms LawOhms Law
Ohms Law
stooty s
 
ELECTROSTATIC INDUCTION
ELECTROSTATIC INDUCTIONELECTROSTATIC INDUCTION
ELECTROSTATIC INDUCTION
Sheeba vinilan
 
Thermal expansion
Thermal expansionThermal expansion
Thermal expansion
Cyrus Vincent Eludo
 
Nature of waves
Nature of wavesNature of waves
Nature of waves
Manuel S. Enverga University Foundation
 
Electrostatics Class 12- Part 2
Electrostatics Class 12- Part 2Electrostatics Class 12- Part 2
Electrostatics Class 12- Part 2
Self-employed
 
presentation_electricity.ppt
presentation_electricity.pptpresentation_electricity.ppt
presentation_electricity.ppt
RKGAMING44
 
Static Electricity
Static ElectricityStatic Electricity
Static Electricity
OhMiss
 
Exp SPA - Chp 16 Static Electricity
Exp SPA - Chp 16 Static ElectricityExp SPA - Chp 16 Static Electricity
Exp SPA - Chp 16 Static Electricity
harrywwh
 
1.1 electric charge
1.1 electric charge1.1 electric charge
1.1 electric charge
sitizalina96
 
4 current and resistance
4 current  and  resistance4 current  and  resistance
4 current and resistance
Ruben Conde
 
ELECTROSTATICS
ELECTROSTATICSELECTROSTATICS
ELECTROSTATICS
KANNAN
 
Solids, Conductors, Insulators & Semiconductors
 Solids, Conductors, Insulators & Semiconductors Solids, Conductors, Insulators & Semiconductors
Solids, Conductors, Insulators & Semiconductors
KamalKhan822
 
Photoelectric effect ppt
Photoelectric effect pptPhotoelectric effect ppt
Photoelectric effect ppt
Santosh Jadhav
 
Electricity and magnetism
Electricity and magnetismElectricity and magnetism
Electricity and magnetism
Rodtips
 
7.4 electromotive force and internal resistance
7.4 electromotive force and internal resistance7.4 electromotive force and internal resistance
7.4 electromotive force and internal resistance
Adlishah Risal Bili
 
ELECTROSTATIC INDUCTION
ELECTROSTATIC INDUCTIONELECTROSTATIC INDUCTION
ELECTROSTATIC INDUCTION
Sheeba vinilan
 
Electrostatics Class 12- Part 2
Electrostatics Class 12- Part 2Electrostatics Class 12- Part 2
Electrostatics Class 12- Part 2
Self-employed
 
presentation_electricity.ppt
presentation_electricity.pptpresentation_electricity.ppt
presentation_electricity.ppt
RKGAMING44
 

Similar to Ch5 Selection Statements (20)

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
NewsMogul
 
Control All
Control AllControl All
Control All
phanleson
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf
2b75fd3051
 
intro to CONTROL STRUCTURES 1 for C++.pptx
intro to CONTROL STRUCTURES 1 for C++.pptxintro to CONTROL STRUCTURES 1 for C++.pptx
intro to CONTROL STRUCTURES 1 for C++.pptx
ragustilo27
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
Prof. Erwin Globio
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
ssuserfb3c3e
 
C fundamental
C fundamentalC fundamental
C fundamental
Selvam Edwin
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
Ahmad Idrees
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
Saad Sheikh
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
ENGWAU TONNY
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
Anil Dutt
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selection
Hamad Odhabi
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
ShivamChaturvedi67
 
Java Script Basics presentation of program
Java Script Basics presentation of programJava Script Basics presentation of program
Java Script Basics presentation of program
MarcosLuis32
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
Praveen M Jigajinni
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
Soran University
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Ashita Agrawal
 
Selection
SelectionSelection
Selection
Jason J Pulikkottil
 
GE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdfGE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdf
Guru Nanak Technical Institutions
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf
2b75fd3051
 
intro to CONTROL STRUCTURES 1 for C++.pptx
intro to CONTROL STRUCTURES 1 for C++.pptxintro to CONTROL STRUCTURES 1 for C++.pptx
intro to CONTROL STRUCTURES 1 for C++.pptx
ragustilo27
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
ssuserfb3c3e
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
Ahmad Idrees
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
Saad Sheikh
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
ENGWAU TONNY
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
Anil Dutt
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selection
Hamad Odhabi
 
Java Script Basics presentation of program
Java Script Basics presentation of programJava Script Basics presentation of program
Java Script Basics presentation of program
MarcosLuis32
 
Ad

More from SzeChingChen (9)

Ch10 Program Organization
Ch10 Program OrganizationCh10 Program Organization
Ch10 Program Organization
SzeChingChen
 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
SzeChingChen
 
Ch8 Arrays
Ch8 ArraysCh8 Arrays
Ch8 Arrays
SzeChingChen
 
Ch7 Basic Types
Ch7 Basic TypesCh7 Basic Types
Ch7 Basic Types
SzeChingChen
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
SzeChingChen
 
Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
SzeChingChen
 
Ch3 Formatted Input/Output
Ch3 Formatted Input/OutputCh3 Formatted Input/Output
Ch3 Formatted Input/Output
SzeChingChen
 
Ch2 C Fundamentals
Ch2 C FundamentalsCh2 C Fundamentals
Ch2 C Fundamentals
SzeChingChen
 
Ch1 Introducing C
Ch1 Introducing CCh1 Introducing C
Ch1 Introducing C
SzeChingChen
 
Ad

Recently uploaded (20)

Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 

Ch5 Selection Statements

  • 1. SC, Chen Ch5 Selection Statement Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2. Ch5 Selection Statement • Operators • Statements Have encountered: 1. return statements 2. Expression statements The three categories of most the remaining statements: 1. Selection statements − If − switch 2. Iteration statements − while − do 3. Jump statements − break − continue − return Other statements 1. Compound statements 2. NULL statement return statement Ch 2.2 Expression statement Ch 4.5
  • 3. Ch5 Selection Statement 5.1 Logical Expressions 5.2 The if Statement 5.3 The switch Statement
  • 4. • Produce 0 (false) or 1 (true) when used in expressions • Can be used to compare integers and floating-point numbers Operands of mixed types allowed • The precedence of the relational operators is lower than that of the arithmetic operators • Left-associative 5.1 Logical Expressions: Relational Operators Symbol Meaning < Less than > Greater than <= Less than or equal to >= Greater then or equal to
  • 5. 5.1 Logical Expressions: Equality Operators • “=“ character in C 1. The assignment operator: single = character (“=“) 2. The equality operator: two adjacent = characters (“==”) • Produce 0 (false) or 1 (true) when used in expressions • Left-associative • The equality operators have lower precedence than the relational operators • The relational and equality operators return integer values Tricky coding using this isn’t a good idea -> hard to read! Symbol Meaning == Equal to != Not equal to i < j == j < k (i < j) == (j < k) (i >= j) + (i == j) The value is 0, 1, or 2
  • 6. 5.1 Logical Expressions: Logical Operators • Produce 0 (false) or 1 (true) when used in expressions 1. Treat any nonzero operand as true value 2. Treat any zero operand as false value • “&&” and “||” short-circuit evaluation of their operands These operators first evaluate the left operand. Then the right operand is evaluated if the value of the expression cannot be deduced from the value of the left operand alone. Side effects may not always occur The ! Operator has the same precedence as the unary plus and minus operators, and is right associative The precedence of && and || is lower than that of the relational and equality operators, and is left associative Symbol Meaning ! Logical negation && Logical and || Logical or (i != 0) && (j / i > 0) (i > 0) && ++j > 0
  • 7. 5.2 The if Statement • The parentheses around the expression are mandatory Part of if statement • If the value of the expression is nonzero, which C interprets as true The statement after the parentheses is executed • Don’t confuse == (equality) with = (assignment) If (i == 0) If (i = 0) -> always false • Often the expression in an if statement will test 1. Whether a variable falls within a range of values: 0 ≤ i < n 2. The opposite condition (outside the range) : i < 0 or i ≥ n if ( expression ) statement If (0 ≤ i && i < n) If (i < 0 || i ≥ n)
  • 8. Equality and Assignment Operators in if • Using if (0 == i) to let compiler produce error message if use “=“ instead of “==“ • Many compilers are capable of checking for suspect uses of the = operator in if conditions GCC compiler will perform check if the –Wparentheses option is used or if –Wall is selected GCC allows the programmer to suppress the warning in a particular case by enclosing the if condition in a second set of parentheses if ( (i == j) ) …
  • 9. 5.2 The if Statement: Compound Statements • Putting braces around a group of statements can force the compiler to treat it as a single statement Each inner statement still ends will a semicolon But the compound statement itself does not • Compound statements are also common in loops and other places where the syntax of C requires a single statement, but we want more than one if ( expression ) { statements } if (line_num == MAX_LINES) { line_num = 0; page_num++; } { line_num = 0; page_num++; }
  • 10. Coding Style for Compound Statements 1. The K&R style 2. The Allman style 3. The Whitesmiths style 4. The GNU style • According to The New Hacker’s Dictionary, there are 4 common styles of indentation and brace placement if (line_num == MAX_LINES) { line_num = 0; page_num++; } if (line_num == MAX_LINES) { line_num = 0; page_num++; } if (line_num == MAX_LINES) { line_num = 0; page_num++; } if (line_num == MAX_LINES) { line_num = 0; page_num++; }
  • 11. 5.2 The if Statement: The else Clause • If the expression in parentheses has the value 0, the statement that follows the word else is executed • Both inner statements end with a semicolon • Coding Style Align else with if If only one short statement, statement can be put on the same line as the if and else if statements can be nested to any depth Adding braces to statements even when they’re not necessary 1. The program becomes easier to modify, because more statements can easily be added to any if or else clause 2. It helps avoid errors that can result from forgetting to use braces when adding statements to an if or else clause if ( expression ) statement else statement
  • 12. 5.2 The if Statement: Cascaded if Statements • Use cascaded if statements to test a series of conditions • C programmers align each else with the original if 1. Avoid the problem of excessive indentation when the number of tests is large 2. Assure the reader that the statement is nothing more than a series of tests if (n < 0) printf (“n is less than 0n”) else if (n == 0) printf (“n is equal to 0n”) else printf (“n is greater than 0n”) if (n < 0) printf (“n is less than 0n”) else if (n == 0) printf (“n is equal to 0n”) else printf (“n is greater than 0n”) if ( expression ) statement else if ( expression ) statement … else if ( expression ) statement else statement
  • 13. 5.2 Calculating a Broker’s Commission • The minimum charge is $39 Transaction size Commission rate Under $2,500 $30 + 1.7% $2,500~$6,250 $56 + 0.66% $6,250~$20,000 $76 + 0.34% $20,000~$50,000 $100 +0.22% $50,000~$500,000 $155 + 0.11% Over$500,000 $255 + 0.09%
  • 14. 5.2 The if Statement: The “Dangling else” Problem 1. C follows the rule that an else clause belongs to the nearest if statement that hasn’t already been paired with an else 2. Using braces can clearly define the pair of if and else if (y != 0) if (x != 0) result = x/y; else printf (“Error: y is equal to 0n”) if (y != 0) if (x != 0) result = x/y; else printf (“Error: y is equal to 0n”) if (y != 0) { if (x != 0) result = x/y; } else printf (“Error: y is equal to 0n”) 1. 2.
  • 15. 5.2 The if Statement: Conditional Expressions (1/2) • Conditional operators (? and : ) 1. Must be used together 2. Allow an expression to produce one or two values depending on the value of a condition 3. Require three operands: ternary operator • expression 1, 2, 3 can be expressions of any type • “if expression1 then expression2 else expression3” 1. expression1 is evaluated first 2. If value of expression1 isn’t zero, then expression2 is evaluated 3. If value of expression1 is zero, then expression3 is the value of the conditional expression1 ? expression2 : expression3 int i, j, k; i = 1; j = 2; k = i > j ? i : j; /* k is now 2 */ k = (i >= 0 ? i : 0)+ j; /* k is now 3 */
  • 16. • Conditional expressions tend to make programs shorter but harder to understand • A few places in which conditional expressions are tempting 1. return statement 2. printf 3. Certain kinds of macro definitions if (i > j) return i; else return j; return i > j ? i : j; if (i > j) printf(“%dn”, i); else printf(“%dn”, j); printf(“%dn”, i > j ? i : j); Macro definitions Ch 14.3 5.2 The if Statement: Conditional Expressions (2/2)
  • 17. Mixed-Types in Conditional Expressions i > 0 ? i : f; i is integer f is floating-point number The expression has type float
  • 18. 5.2 The if Statement: Boolean Value in C89 • The C language lacked a proper Boolean type for many years There is no defined in the C89 standard • Work around 1. Declare an int variable and then assign it either 0 or 1 Not contribute much to program readability It is not obvious that flag is to be assigned only Boolean values 2. Define macros with names such as TRUE and FALSE 3. Carry 2. idea one step further, we can define a macro that can be used as a type BOOL can take the place of int when declaring Boolean variables 4. Better way in later chapter by using type definition and enumerations #define TRUE 1 #define FALSE 0 Test whether flag is True False 1st way if (flag == TRUE) … if (flag == FALSE) … 2nd way if (flag) … if (!flag) … Better way 1. More concise 2. Still work correctly if flag has a value other than 0 or 1 int flag flag = 0; … flag = 1; #define BOOL int; BOOL flag;type definitions Ch 7.5 enumerations Ch 16.5
  • 19. 5.2 The if Statement: Boolean Values in C99 • C99 provides the _Bool type An unsigned integer type Can only be assigned 0 or 1 − Attempt to store a nonzero value into a _Bool variable will cause the variable to be assigned 1 Is legal to − Perform arithmetic on _Bool variables − Print a _Bool variables − Test _Bool variables in an if statement •C99 also provides a new header <stdbool.h> Provide a macro, bool, that stands for _Bool Supply macros named true and false #include <stdbool.h> … bool flag; _Bool flag; Unsigned integer types Ch 7.1 <stdbool.h> header Ch 21.5
  • 20. _Bool in C99 • Why use _Bool instead of bool or Boolean? Existing C programs might already define these names, causing older code not to compile The C89 standard specifics that names beginning with an underscore followed by an uppercase letter are reserved for future use and should not be used by programmers
  • 21. 5.3 The switch Statement (1/3) • As an alternative to cascaded if statement, C provides the switch statement Easier to read than cascaded if statement Often faster than if statements if (grade == 4) printf (“Excellent”); else if (grade == 3) printf (“Good”); else if (grade == 2) printf (“Average”); else if (grade == 1) printf (“Poor”); else if (grade == 0) printf (“Failed”); else printf (“Illegal grade”); switch (grade) { case 4: printf (“Excellent”); break; case 3: printf (“Good”); break; case 2: printf (“Average”); break; case 1: printf (“Poor”); break; case 0: printf (“Failed”); break; default: printf (“Illegal grade”); break; } break statement Ch 6.4 Transfer control to the statement following the switch If the value of grade doesn’t match any of the choices listed, the default case apply default 1. Doesn’t need to come last 2. Not required Control simply passes to the next statement after the switch if default is missing and the value of the controlling expression doesn’t match any of the case labels
  • 22. 5.3 The switch Statement (2/3) switch ( expression ) { case constant-expression : statements … case constant-expression : statements default : statements } Controlling expression 1. Integer expression 2. Characters are treated as integers in C 3. Floating-point numbers and strings don’t qualify Case labels 1. Each case begins with a label 2. constant-expression 1. Ordinary expression 2. Except it can’t contain variables or function calls 3. An integer (characters are also OK) Statements 1. No braces are required around the statements 2. The last statement in each group is normally break characters Ch 7.3
  • 23. 5.3 The switch Statement (3/3) • Duplicated case labels aren’t allowed • The order of the cases doesn’t matter • Only one constant expression may follow the word case Several case labels may precede the same group of statements • There is no way to write a case label that specifies a range of values switch (grade) { case 4: case 3: case 2: case 1: printf (“Passing”); break; case 0: printf (“Failed”); break; default: printf (“Illegal grade”); break; } switch (grade) { case 4: case 3: case 2: case 1: printf (“Passing”); break; case 0: printf (“Failed”); break; default: printf (“Illegal grade”); break; }
  • 24. 5.3 The switch Statement: The Role of the break Statement • switch statement is a form of “computed jump” When the controlling expression is evaluated, control jumps to the case label matching the value of the switch expression A case label is just a position marker within the switch When the last statement in the case has been executed, control “falls through” to the first statement in the following case − The case label for the next case is ignored • Falling through from one case into the next is rare It is good to point out any deliberate omission of break • The last case in a switch statement is common to put one break there If cases should later be added switch (grade) { case 4: case 3: case 2: case 1: num_passing++; /*FALL THROUGH*/ case 0: total_grade++; break; } switch (grade) { case 4: printf (“Excellent”); case 3: printf (“Good”); case 2: printf (“Average”); case 1: printf (“Poor”); case 0: printf (“Failed”); default: printf (“Illegal grade”); }
  • 25. 5.3 Printing a Date in Legal Form
  • 26. Other Form for switch Statement? • The switch statement is b bit more general than described in this chapter A switch statement can contain labels that aren’t preceded by the word case switch (…) { … defualt: … } switch ( expression ) { case constant-expression : statements … case constant-expression : statements default : statements } switch ( expression ) statements Also legal, because “default” is an ordinary label
  • 27. Coding Style of switch 1. Put the statements in each case after the case label Fine when the statements in each case are short and there are relatively few of them 2. Put the statements under the case label, indenting the statements to make the case label stand out Better for large switch statements in which the statements in each case are complex and/or numerous switch (grade) { case 4: printf (“Excellent”); break; case 3: printf (“Good”); break; default: printf (“Failed”); break; } switch (grade) { case 4: printf (“Excellent”); break; case 3: printf (“Good”); break; default: printf (“Failed”); break; } • There are at least two common methods switch (grade) { case 4: printf (“Excellent”); break; case 3: printf (“Good”); break; default: printf (“Failed”); break; }

Editor's Notes