SlideShare a Scribd company logo
1 of 21
Control Structures
Sequential execution
Statements executed one after the other in the order
written
Transfer of control
When the next statement executed is not the next one
in sequence
Bohm and Jacopini: all programs written in terms
of 3 control structures
Sequence structure
Built into C++. Programs executed sequentially by default.
Selection structures
C++ has three types - if, if/else, and switch
Repetition structures
C++ has three types - while, do/while, and for
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols
connected by arrows called flowlines.
– Rectangle symbol (action symbol)
• Indicates any type of action.
– Oval symbol
• indicates beginning or end of a program, or a section of code
(circles).
• single-entry/single-exit control structures
– Connect exit point of one control structure to entry
point of the next (control-structure stacking).
– Makes programs easy to build.
The if Selection Structure
• Selection structure
– used to 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 and program goes on to next statement
– If the condition is false
• print statement is ignored and the program goes onto the next
statement
– Indenting makes programs easier to read
• C++ ignores whitespace characters
The if Selection Structure
• Translation of pseudocode statement into C++:
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 the condition, follow appropriate path
• if structure is a single-entry/single-exit
structure
• Flowchart of pseudo code statement
true
false
grade >= 60 print “Passed”
A decision can be made on
any expression.
zero - false
nonzero - true
Example:
3 - 4 is true
The if/else Selection Structure
• if
– Only performs an action if the condition is true
• if/else
– A different action is performed when condition is true and
when condition is false
• Psuedocode
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";
The if/else Selection Structure
• Ternary conditional operator (?:)
– Takes three arguments (condition, value if true,
value if false)
• Our pseudocode could be written:
cout << ( grade >= 60 ? “Passed” :
“Failed” );
truefalse
print “Failed” print “Passed”
grade >= 60
The if/else Selection Structure
• Nested if/else structures
– Test for multiple cases by placing if/else selection structures
inside if/else selection structures.
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”
– Once a condition is met, the rest of the statements are skipped
The if/else Selection Structure
• Compound statement:
– Set of statements within a pair of braces
– Example:
if ( grade >= 60 )
cout << "Passed.n";
else {
cout << "Failed.n";
cout << "You must take this course
again.n";
}
– Without the braces,
cout << "You must take this course again.n";
would be automatically executed
• Block
– Compound statements with declarations
The if/else Selection Structure
• Syntax errors
– Errors caught by compiler
• Logic errors
– Errors which have their effect at execution time
• Non-fatal logic errors
– program runs, but has incorrect output
• Fatal logic errors
– program exits prematurely
The while Repetition Structure
• Repetition structure
– Programmer specifies an action to be repeated while
some condition remains true
– Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false.
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
The while Repetition Structure
• Flowchart of while loop
product <=
1000
product = 2 *
product
tru
e
fals
e
Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires:
– The name of a control variable (or loop counter).
– The initial value of the control variable.
– The condition that tests for the final value of the control
variable (i.e., whether looping should continue).
– The increment (or decrement) by which the control variable
is modified each time through the loop.
• Example:
int counter =1; //initialization
while (counter <= 10){ //repetition
condition
cout << counter << endl;
++counter; //increment
}
Essentials of Counter-Controlled
Repetition
• The declaration
int counter = 1;
– Names counter
– Declares counter to be an integer
– Reserves space for counter in memory
– Sets counter to an initial value of 1
The for Repetition Structure
• The general format when using for loops is
for ( initialization; LoopContinuationTest;
increment )
statement
• Example:
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
– Prints the integers from one to ten
The for Repetition Structure
• For loops can usually be rewritten as while
loops:
initialization;
while ( loopContinuationTest){
statement
increment;
}
• Initialization and increment as comma-separated
lists
for (int i = 0, j = 0; j + i <= 10; j++,
i++)
cout << j + i << endl;
The switch Multiple-Selection
Structure
• switch
– Useful when variable or expression is tested for multiple values
– Consists of a series of case labels and an optional default
case
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)
The do/while Repetition Structure
• The do/while repetition structure is similar to the
while structure,
– Condition for repetition tested after the body of the loop is
executed
• Format:
do {
statement
} while ( condition );
• Example (letting counter = 1):
do {
cout << counter << " ";
} while (++counter <= 10);
– This prints the integers from 1 to 10
• All actions are performed at least once.
true
false
action(s)
condition
The break and continue
Statements
• Break
– Causes immediate exit from a while, for,
do/while or switch structure
– Program execution continues with the first
statement after the structure
– Common uses of the break statement:
• Escape early from a loop
• Skip the remainder of a switch structure
The break and continue
Statements
• Continue
– Skips the remaining statements in the body of a
while, for or do/while structure and
proceeds with the next iteration of the loop
– In while and do/while, the loop-continuation
test is evaluated immediately after the continue
statement is executed
– In the for structure, the increment expression is
executed, then the loop-continuation test is
evaluated
Structured-Programming Summary
• All programs can be broken down into
– Sequence
– Selection
• if, if/else, or switch
• Any selection can be rewritten as an if statement
– Repetition
• while, do/while or for
• Any repetition structure can be rewritten as a while
statement

More Related Content

What's hot

0.0 Introduction to theory of computation
0.0 Introduction to theory of computation0.0 Introduction to theory of computation
0.0 Introduction to theory of computationSampath Kumar S
 
AUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESAUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESsuthi
 
Church Turing Thesis
Church Turing ThesisChurch Turing Thesis
Church Turing ThesisHemant Sharma
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environmentIffat Anjum
 
Introduction number systems and conversion
 Introduction number systems and conversion Introduction number systems and conversion
Introduction number systems and conversionkanyuma jitjumnong
 
Mealy moore machine model
Mealy moore machine modelMealy moore machine model
Mealy moore machine modeldeepinderbedi
 
Huffman Tree And Its Application
Huffman Tree And Its ApplicationHuffman Tree And Its Application
Huffman Tree And Its ApplicationPapu Kumar
 
System programming note
System programming noteSystem programming note
System programming noteSANTOSH RATH
 
Introduction to Compiler Construction
Introduction to Compiler Construction Introduction to Compiler Construction
Introduction to Compiler Construction Sarmad Ali
 
Cyrus beck line clipping algorithm
Cyrus beck line clipping algorithmCyrus beck line clipping algorithm
Cyrus beck line clipping algorithmPooja Dixit
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysisIffat Anjum
 
Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )swapnac12
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical AnalyzerArchana Gopinath
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semanticsalvin567
 

What's hot (20)

0.0 Introduction to theory of computation
0.0 Introduction to theory of computation0.0 Introduction to theory of computation
0.0 Introduction to theory of computation
 
AUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESAUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTES
 
Theory of computation and automata
Theory of computation and automataTheory of computation and automata
Theory of computation and automata
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Church Turing Thesis
Church Turing ThesisChurch Turing Thesis
Church Turing Thesis
 
Answer quiz minimax
Answer quiz minimaxAnswer quiz minimax
Answer quiz minimax
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Introduction number systems and conversion
 Introduction number systems and conversion Introduction number systems and conversion
Introduction number systems and conversion
 
Mealy moore machine model
Mealy moore machine modelMealy moore machine model
Mealy moore machine model
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
 
Huffman Tree And Its Application
Huffman Tree And Its ApplicationHuffman Tree And Its Application
Huffman Tree And Its Application
 
System programming note
System programming noteSystem programming note
System programming note
 
Introduction to Compiler Construction
Introduction to Compiler Construction Introduction to Compiler Construction
Introduction to Compiler Construction
 
Cyrus beck line clipping algorithm
Cyrus beck line clipping algorithmCyrus beck line clipping algorithm
Cyrus beck line clipping algorithm
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysis
 
Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
Overview of Computer Graphics
Overview of Computer GraphicsOverview of Computer Graphics
Overview of Computer Graphics
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semantics
 

Similar to Control Structures Explained: Sequential, Selection, Repetition

control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
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
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptSuleman Khan
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Blue Elephant Consulting
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computingNUST Stuff
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structuresayshasafdarwaada
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
NRG 106_Session 4_CLanguage.pptx
NRG 106_Session 4_CLanguage.pptxNRG 106_Session 4_CLanguage.pptx
NRG 106_Session 4_CLanguage.pptxKRIPABHARDWAJ1
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.pptRahul Borate
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxSKUP1
 

Similar to Control Structures Explained: Sequential, Selection, Repetition (20)

control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
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...
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Arrays
ArraysArrays
Arrays
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
NRG 106_Session 4_CLanguage.pptx
NRG 106_Session 4_CLanguage.pptxNRG 106_Session 4_CLanguage.pptx
NRG 106_Session 4_CLanguage.pptx
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.ppt
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Control structure
Control structureControl structure
Control structure
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 

Recently uploaded

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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
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
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

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🔝
 
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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
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
 
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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Control Structures Explained: Sequential, Selection, Repetition

  • 1. Control Structures Sequential execution Statements executed one after the other in the order written Transfer of control When the next statement executed is not the next one in sequence Bohm and Jacopini: all programs written in terms of 3 control structures Sequence structure Built into C++. Programs executed sequentially by default. Selection structures C++ has three types - if, if/else, and switch Repetition structures C++ has three types - while, do/while, and for
  • 2. • Flowchart – Graphical representation of an algorithm – Drawn using certain special-purpose symbols connected by arrows called flowlines. – Rectangle symbol (action symbol) • Indicates any type of action. – Oval symbol • indicates beginning or end of a program, or a section of code (circles). • single-entry/single-exit control structures – Connect exit point of one control structure to entry point of the next (control-structure stacking). – Makes programs easy to build.
  • 3. The if Selection Structure • Selection structure – used to 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 and program goes on to next statement – If the condition is false • print statement is ignored and the program goes onto the next statement – Indenting makes programs easier to read • C++ ignores whitespace characters
  • 4. The if Selection Structure • Translation of pseudocode statement into C++: 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 the condition, follow appropriate path • if structure is a single-entry/single-exit structure
  • 5. • Flowchart of pseudo code statement true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 is true
  • 6. The if/else Selection Structure • if – Only performs an action if the condition is true • if/else – A different action is performed when condition is true and when condition is false • Psuedocode 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";
  • 7. The if/else Selection Structure • Ternary conditional operator (?:) – Takes three arguments (condition, value if true, value if false) • Our pseudocode could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); truefalse print “Failed” print “Passed” grade >= 60
  • 8. The if/else Selection Structure • Nested if/else structures – Test for multiple cases by placing if/else selection structures inside if/else selection structures. 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” – Once a condition is met, the rest of the statements are skipped
  • 9. The if/else Selection Structure • Compound statement: – Set of statements within a pair of braces – Example: if ( grade >= 60 ) cout << "Passed.n"; else { cout << "Failed.n"; cout << "You must take this course again.n"; } – Without the braces, cout << "You must take this course again.n"; would be automatically executed • Block – Compound statements with declarations
  • 10. The if/else Selection Structure • Syntax errors – Errors caught by compiler • Logic errors – Errors which have their effect at execution time • Non-fatal logic errors – program runs, but has incorrect output • Fatal logic errors – program exits prematurely
  • 11. The while Repetition Structure • Repetition structure – Programmer specifies an action to be repeated while some condition remains true – Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list – while loop repeated until condition becomes false. • Example int product = 2; while ( product <= 1000 ) product = 2 * product;
  • 12. The while Repetition Structure • Flowchart of while loop product <= 1000 product = 2 * product tru e fals e
  • 13. Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires: – The name of a control variable (or loop counter). – The initial value of the control variable. – The condition that tests for the final value of the control variable (i.e., whether looping should continue). – The increment (or decrement) by which the control variable is modified each time through the loop. • Example: int counter =1; //initialization while (counter <= 10){ //repetition condition cout << counter << endl; ++counter; //increment }
  • 14. Essentials of Counter-Controlled Repetition • The declaration int counter = 1; – Names counter – Declares counter to be an integer – Reserves space for counter in memory – Sets counter to an initial value of 1
  • 15. The for Repetition Structure • The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement • Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; – Prints the integers from one to ten
  • 16. The for Repetition Structure • For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest){ statement increment; } • Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl;
  • 17. The switch Multiple-Selection Structure • switch – Useful when variable or expression is tested for multiple values – Consists of a series of case labels and an optional default case 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)
  • 18. The do/while Repetition Structure • The do/while repetition structure is similar to the while structure, – Condition for repetition tested after the body of the loop is executed • Format: do { statement } while ( condition ); • Example (letting counter = 1): do { cout << counter << " "; } while (++counter <= 10); – This prints the integers from 1 to 10 • All actions are performed at least once. true false action(s) condition
  • 19. The break and continue Statements • Break – Causes immediate exit from a while, for, do/while or switch structure – Program execution continues with the first statement after the structure – Common uses of the break statement: • Escape early from a loop • Skip the remainder of a switch structure
  • 20. The break and continue Statements • Continue – Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop – In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed – In the for structure, the increment expression is executed, then the loop-continuation test is evaluated
  • 21. Structured-Programming Summary • All programs can be broken down into – Sequence – Selection • if, if/else, or switch • Any selection can be rewritten as an if statement – Repetition • while, do/while or for • Any repetition structure can be rewritten as a while statement