SlideShare a Scribd company logo
1 of 25
1
Lecture 3
Control Structures
Selection: else/if and switch
2
2.1 Introduction
 Before writing a program
 Have a thorough understanding of problem
 Carefully plan your approach for solving it
 While writing a program
 Know what “building blocks” are available
 Use good programming principles
3
2.2 Algorithms
 Computing problems
 Solved by executing a series of actions in a
specific order
 Algorithm is a procedure determining
 Actions to be executed
 Order to be executed
 Example: recipe
 Program control
 Specifies the order in which statements are
executed
4
2.3 Pseudocode
 Pseudocode
 Artificial, informal language used to develop
algorithms
 Similar to everyday English
 Not executed on computers
 Used to think out program before coding
 Easy to convert into C++ program
 Only executable statements
 No need to declare variables
5
2.4 Control Structures
 Sequential execution
 Statements executed in order
 Transfer of control
 Next statement executed not next one in sequence
 3 control structures (Bohm and Jacopini)
 Sequence structure
 Programs executed sequentially by default
 Selection structures
 if, if/else, switch
 Repetition structures
 while, do/while, for
6
2.4 Control Structures
 C++ keywords
 Cannot be used as identifiers or variable names
C++ Keywords
Keywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
7
2.4 Control Structures
 Flowchart
 Graphical representation of an algorithm
 Special-purpose symbols connected by arrows (flowlines)
 Rectangle symbol (action symbol)
 Any type of action
 Oval symbol
 Beginning or end of a program, or a section of code (circles)
 Single-entry/single-exit control structures
 Connect exit point of one to entry point of the next
 Control structure stacking
8
2.5 if Selection Structure
 Selection structure
 Choose among alternative courses of action
 Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
 If the condition is true
 Print statement executed, program continues to next
statement
 If the condition is false
 Print statement ignored, program continues
 Indenting makes programs easier to read
 C++ ignores whitespace characters (tabs, spaces, etc.)
9
2.5 if Selection Structure
 Translation into C++
If student’s grade is greater than or equal to 60
Print “Passed”
if ( grade >= 60 )
cout << "Passed";
 Diamond symbol (decision symbol)
 Indicates decision is to be made
 Contains an expression that can be true or false
 Test condition, follow path
 if structure
 Single-entry/single-exit
10
2.5 if Selection Structure
 Flowchart of pseudocode statement
true
false
grade >= 60 print “Passed”
A decision can be made on
any expression.
zero - false
nonzero - true
Example:
3 - 4 is true
11
2.6 if/else Selection Structure
 if
 Performs action if condition true
 if/else
 Different actions if conditions true or false
 Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
 C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
12
2.6 if/else Selection Structure
 Nested if/else structures
 One inside another, test for multiple cases
 Once condition met, other statements skipped
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”
13
2.6 if/else Selection Structure
 Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
14
Importance of Curly Braces
 Print “We have a problem” if examGrade < 60
 Print “We have a real problem” if examGrade < 60 and
quizGrade < 10
 Print “Ok” if examGrade >= 60
int examGrade, quizGrade;
if (examGrade < 60)
cout << “We have a problem” << endl;
if (quizGrade < 10)
cout << “We have a real problem” << endl;
else
cout << “Ok”;
15
Exam Grade Flowchartint examGrade, quizGrade;
if (examGrade < 60)
cout << “We have a problem” << endl;
if (quizGrade < 10)
cout << “We have a real problem” << endl;
else
cout << “Ok”;
examGrade < 60
“We have a problem”
“We have a real problem”
true
quizGrade < 10
“Ok”
truefalse
16
Writing Cases
 Print “We have a problem” if examGrade < 60
 Print “We have a real problem” if examGrade < 60 and
quizGrade < 10
 Print “Ok” if examGrade >= 60
examGrade < 60 quizGrade < 10 Action
Case 1 true false “We have a problem”
Case 2 true true “We have a problem” and
“We have a real problem”
Case 3 false true/false “Ok”
17
Putting it all together
examGrade < 60 quizGrade < 10 Action
Case 1 true false “We have a problem”
Case 2 true true “We have a problem” and
“We have a real problem”
Case 3 false true/false “Ok”
int examGrade, quizGrade;
if (examGrade < 60)
System.out.println(“We have a problem”);
if (quizGrade < 10)
System.out.printl(“We have a real problem”);
else
System.out.println(“Ok”);
int examGrade, quizGrade;
if (examGrade < 60) {
cout << “We have a problem” << endl;
if (quizGrade < 10)
cout << “We have a real problem” << endl;
}
else
cout << “Ok”;
18
boolean Operators
 Combines multiple boolean expressions
 If person’s age greater than or equal to 13 and less
than 17, he can go to G and PG-13 rated movies,
but not R rated movies
 if (age >= 13 && age < 17)
cout << “You can go to G and PG-13”
<< “ rated movies, but not R” +
<< “ rated movies.”) << endl;
 boolean operators
 and - && (true if all conditions are true)
 or - || (true if one condition is true)
 not - ! (true if conditions is false)
19
Expression Combinations
operand1 operand2 operand1 && operand2
true true true
true false false
false true false
false false false
if (age >= 13 && age < 17)
cout << “You can go to G and PG-13”
<< “ rated movies, but not R” +
<< “ rated movies.” << endl;
Let age = 12
Let age = 16
Let age = 17
The && (and) operator
20
Expression Combinations
operand1 operand2 operand1 || operand2
true true true
true false true
false true true
false false false
The || (or) operator
operand !operand
true false
false true
The ! (not) operator
Example
if ( !( grade == sentinelValue ) )
cout << "The next grade is "
<< grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is "
<< grade << endl;
21
Playing Cards
 Exercise with playing cards
 Numbers represent the rank and suit of cards
// Codes for suits
const int SPADES = 0;
const int HEARTS = 1;
const int DIAMONDS = 2;
const int CLUBS = 3;
// Codes for nonnumeric ranks
const int ACE = 1;
const int JACK = 11;
const int QUEEN = 12;
const int KING = 13;
22
Prints a Card Name
 Print “rank of suit”
 Consider just the rank part
if (rank == JACK)
cout << "Jack";
else if (rank == QUEEN)
cout << "Queen";
else if (rank == KING;
cout << "King";
else if (rank == ACE)
cout << "Ace";
else
cout << rank;
Notice:
comparing rank to
a number of
different value
23
2.16switch Multiple-Selection
Structure
 switch
 Test variable for multiple values
 Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
default: // taken if variable matches no other cases
statements
break;
}
24
2.16switch Multiple-Selection
Structure
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
25
Converting if/else to a switch
if (rank == JACK)
cout << "Jack";
else if (rank == QUEEN)
cout << "Queen";
else if (rank == KING;
cout << "King";
else if (rank == ACE)
cout << "Ace";
else
cout << rank;
switch (rank)
{
case JACK:
cout << "Jack";
break;
case QUEEN:
cout << "Queen";
break;
case KING:
cout << "King";
break;
case ACE:
cout << "Ace";
break;
default:
cout << rank;
}

More Related Content

Viewers also liked

Muresan valentina
Muresan valentinaMuresan valentina
Muresan valentinak2hagen
 
Simileanu alex
Simileanu alexSimileanu alex
Simileanu alexk2hagen
 
Итоги I четерти 2015 начальная школа
Итоги I четерти 2015 начальная школаИтоги I четерти 2015 начальная школа
Итоги I четерти 2015 начальная школаMarinaDock
 
Sistemas operativos
Sistemas operativosSistemas operativos
Sistemas operativosCarlosgl99
 

Viewers also liked (7)

CV Winda Gardena
CV Winda GardenaCV Winda Gardena
CV Winda Gardena
 
Ch4
Ch4Ch4
Ch4
 
Muresan valentina
Muresan valentinaMuresan valentina
Muresan valentina
 
Simileanu alex
Simileanu alexSimileanu alex
Simileanu alex
 
Ch3
Ch3Ch3
Ch3
 
Итоги I четерти 2015 начальная школа
Итоги I четерти 2015 начальная школаИтоги I четерти 2015 начальная школа
Итоги I четерти 2015 начальная школа
 
Sistemas operativos
Sistemas operativosSistemas operativos
Sistemas operativos
 

Similar to Ch3.1

cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptSuleman Khan
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computingNUST Stuff
 
Control Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxControl Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxdoncreiz1
 
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...ronistgdr
 
C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2Ammara Javed
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.ppt11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.pptAnjali127411
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 

Similar to Ch3.1 (20)

cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
 
Fekra c++ Course #2
Fekra c++ Course #2Fekra c++ Course #2
Fekra c++ Course #2
 
C++ IF STATMENT AND ITS TYPE
C++ IF STATMENT AND ITS TYPEC++ IF STATMENT AND ITS TYPE
C++ IF STATMENT AND ITS TYPE
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
Control Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxControl Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptx
 
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.ppt11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.ppt
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
lesson 2.pptx
lesson 2.pptxlesson 2.pptx
lesson 2.pptx
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 

Recently uploaded

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Recently uploaded (20)

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Ch3.1

  • 2. 2 2.1 Introduction  Before writing a program  Have a thorough understanding of problem  Carefully plan your approach for solving it  While writing a program  Know what “building blocks” are available  Use good programming principles
  • 3. 3 2.2 Algorithms  Computing problems  Solved by executing a series of actions in a specific order  Algorithm is a procedure determining  Actions to be executed  Order to be executed  Example: recipe  Program control  Specifies the order in which statements are executed
  • 4. 4 2.3 Pseudocode  Pseudocode  Artificial, informal language used to develop algorithms  Similar to everyday English  Not executed on computers  Used to think out program before coding  Easy to convert into C++ program  Only executable statements  No need to declare variables
  • 5. 5 2.4 Control Structures  Sequential execution  Statements executed in order  Transfer of control  Next statement executed not next one in sequence  3 control structures (Bohm and Jacopini)  Sequence structure  Programs executed sequentially by default  Selection structures  if, if/else, switch  Repetition structures  while, do/while, for
  • 6. 6 2.4 Control Structures  C++ keywords  Cannot be used as identifiers or variable names C++ Keywords Keywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
  • 7. 7 2.4 Control Structures  Flowchart  Graphical representation of an algorithm  Special-purpose symbols connected by arrows (flowlines)  Rectangle symbol (action symbol)  Any type of action  Oval symbol  Beginning or end of a program, or a section of code (circles)  Single-entry/single-exit control structures  Connect exit point of one to entry point of the next  Control structure stacking
  • 8. 8 2.5 if Selection Structure  Selection structure  Choose among alternative courses of action  Pseudocode example: If student’s grade is greater than or equal to 60 Print “Passed”  If the condition is true  Print statement executed, program continues to next statement  If the condition is false  Print statement ignored, program continues  Indenting makes programs easier to read  C++ ignores whitespace characters (tabs, spaces, etc.)
  • 9. 9 2.5 if Selection Structure  Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed";  Diamond symbol (decision symbol)  Indicates decision is to be made  Contains an expression that can be true or false  Test condition, follow path  if structure  Single-entry/single-exit
  • 10. 10 2.5 if Selection Structure  Flowchart of pseudocode statement true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 is true
  • 11. 11 2.6 if/else Selection Structure  if  Performs action if condition true  if/else  Different actions if conditions true or false  Pseudocode if student’s grade is greater than or equal to 60 print “Passed” else print “Failed”  C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";
  • 12. 12 2.6 if/else Selection Structure  Nested if/else structures  One inside another, test for multiple cases  Once condition met, other statements skipped 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”
  • 13. 13 2.6 if/else Selection Structure  Example if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // 80-89 cout << "B"; else if ( grade >= 70 ) // 70-79 cout << "C"; else if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F";
  • 14. 14 Importance of Curly Braces  Print “We have a problem” if examGrade < 60  Print “We have a real problem” if examGrade < 60 and quizGrade < 10  Print “Ok” if examGrade >= 60 int examGrade, quizGrade; if (examGrade < 60) cout << “We have a problem” << endl; if (quizGrade < 10) cout << “We have a real problem” << endl; else cout << “Ok”;
  • 15. 15 Exam Grade Flowchartint examGrade, quizGrade; if (examGrade < 60) cout << “We have a problem” << endl; if (quizGrade < 10) cout << “We have a real problem” << endl; else cout << “Ok”; examGrade < 60 “We have a problem” “We have a real problem” true quizGrade < 10 “Ok” truefalse
  • 16. 16 Writing Cases  Print “We have a problem” if examGrade < 60  Print “We have a real problem” if examGrade < 60 and quizGrade < 10  Print “Ok” if examGrade >= 60 examGrade < 60 quizGrade < 10 Action Case 1 true false “We have a problem” Case 2 true true “We have a problem” and “We have a real problem” Case 3 false true/false “Ok”
  • 17. 17 Putting it all together examGrade < 60 quizGrade < 10 Action Case 1 true false “We have a problem” Case 2 true true “We have a problem” and “We have a real problem” Case 3 false true/false “Ok” int examGrade, quizGrade; if (examGrade < 60) System.out.println(“We have a problem”); if (quizGrade < 10) System.out.printl(“We have a real problem”); else System.out.println(“Ok”); int examGrade, quizGrade; if (examGrade < 60) { cout << “We have a problem” << endl; if (quizGrade < 10) cout << “We have a real problem” << endl; } else cout << “Ok”;
  • 18. 18 boolean Operators  Combines multiple boolean expressions  If person’s age greater than or equal to 13 and less than 17, he can go to G and PG-13 rated movies, but not R rated movies  if (age >= 13 && age < 17) cout << “You can go to G and PG-13” << “ rated movies, but not R” + << “ rated movies.”) << endl;  boolean operators  and - && (true if all conditions are true)  or - || (true if one condition is true)  not - ! (true if conditions is false)
  • 19. 19 Expression Combinations operand1 operand2 operand1 && operand2 true true true true false false false true false false false false if (age >= 13 && age < 17) cout << “You can go to G and PG-13” << “ rated movies, but not R” + << “ rated movies.” << endl; Let age = 12 Let age = 16 Let age = 17 The && (and) operator
  • 20. 20 Expression Combinations operand1 operand2 operand1 || operand2 true true true true false true false true true false false false The || (or) operator operand !operand true false false true The ! (not) operator Example if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Alternative: if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;
  • 21. 21 Playing Cards  Exercise with playing cards  Numbers represent the rank and suit of cards // Codes for suits const int SPADES = 0; const int HEARTS = 1; const int DIAMONDS = 2; const int CLUBS = 3; // Codes for nonnumeric ranks const int ACE = 1; const int JACK = 11; const int QUEEN = 12; const int KING = 13;
  • 22. 22 Prints a Card Name  Print “rank of suit”  Consider just the rank part if (rank == JACK) cout << "Jack"; else if (rank == QUEEN) cout << "Queen"; else if (rank == KING; cout << "King"; else if (rank == ACE) cout << "Ace"; else cout << rank; Notice: comparing rank to a number of different value
  • 23. 23 2.16switch Multiple-Selection Structure  switch  Test variable for multiple values  Series of case labels and optional default case switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 statements break; default: // taken if variable matches no other cases statements break; }
  • 24. 24 2.16switch Multiple-Selection Structure true false . . . case a case a action(s) break case b case b action(s) break false false case z case z action(s) break true true default action(s)
  • 25. 25 Converting if/else to a switch if (rank == JACK) cout << "Jack"; else if (rank == QUEEN) cout << "Queen"; else if (rank == KING; cout << "King"; else if (rank == ACE) cout << "Ace"; else cout << rank; switch (rank) { case JACK: cout << "Jack"; break; case QUEEN: cout << "Queen"; break; case KING: cout << "King"; break; case ACE: cout << "Ace"; break; default: cout << rank; }