SlideShare a Scribd company logo
1 of 27
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;
}

More Related Content

What's hot

What's hot (19)

Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
C language
C languageC language
C language
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
Ch03
Ch03Ch03
Ch03
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Ch09
Ch09Ch09
Ch09
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Ch04
Ch04Ch04
Ch04
 
Pc module1
Pc module1Pc module1
Pc module1
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Ch05
Ch05Ch05
Ch05
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
C programming part4
C programming part4C programming part4
C programming part4
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 

Similar to Ch5 Selection Statements

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf2b75fd3051
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad 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 controlENGWAU TONNY
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selectionHamad Odhabi
 
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.pdfAsst.prof M.Gokilavani
 

Similar to Ch5 Selection Statements (20)

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
 
Control All
Control AllControl All
Control All
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
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
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selection
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Selection
SelectionSelection
Selection
 
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
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
C tutorial
C tutorialC tutorial
C tutorial
 

Recently uploaded

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 

Recently uploaded (20)

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 

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

  1. 舉例子
  2. 舉例子
  3. 舉例子
  4. 舉例子
  5. 舉例子
  6. 舉例子
  7. 舉例子
  8. 舉例子
  9. 舉例子
  10. 舉例子
  11. 舉例子
  12. 舉例子
  13. 舉例子
  14. 舉例子