SlideShare a Scribd company logo
Introduction to Computer Programming
Control Structures – Repetition
C++ Programming: From Problem Analysis to Program Design
1
• Basic loop structures
• while loops
• Interactive while loops
• for loops
• Loop programming techniques
• Nested loops
• do whileloops
• Common programming errors
Chapter Topics
2
• Suppose you want to add five numbers to find their
average. From what you have learned so far, you
could proceed as follows:
• Assume that all variables are properly declared
Why Is Repetition Needed?
3
Why Is Repetition Needed?
• Suppose you want to add and average 100, 1000, or
more numbers
– You would have to declare that many variables
– List them again in cin statements
• This takes an exorbitant amount of space and time
• Also, if you want to run this program again with
different values or with a different number of
values, you have to rewrite the program
4
• Suppose you want to add the following numbers:
5 3 7 9 4
• Consider the following statements, in which sum
and num are variables of type int:
1. sum = 0;
2. cin >> num;
3. sum = sum + num;
• Each time you need to add a new number, you
repeat statements 2 and 3
Why Is Repetition Needed?
5
• Repetition structure has four required elements:
– Repetition statement
– Condition to be evaluated
– Initial value for the condition
– Loop termination
• Repetition statements include:
– while
– for
– do while
Basic Loop Structures
6
f o r ( i = 0 ; i < 1 0 ; i + + )
c o u t < < i ;
• The condition can be tested
– At the beginning: Pretest or entrance‐controlled loop
(while, for)
– At the end: Posttest or exit‐controlled loop (do‐while)
• Something in the loop body must cause the
condition to change, to avoid an infinite loop, which
never terminates
Basic Loop Structures (continued)
7
• Pretest loop: Condition
is tested first; if false,
statements in the loop
body are never
executed
• while and for loops
are pretest loops
Pretest and Posttest Loops
A pretest loop
8
Pretest and Posttest Loops (continued)
• Posttest loop: Condition is
tested after the loop body
statements are executed;
loop body always executes
at least once
• do while is a posttest
loop
A posttest loop
9
• Fixed‐count loop: Loop is processed for a fixed
number of repetitions
• Variable‐condition loop: Number of repetitions
depends on the value of a variable
Fixed‐Count Versus Variable‐Condition
Loops
10
f o r ( i = 0 ; i < 1 0 ; i + + )
c o u t < < i ;
f o r ( i = 0 ; i < a ; i + + )
c o u t < < i ;
while Loops
• while statement is used to create a while loop
– Syntax:
while (expression)
statement;
• Statements following the expressions are executed
as long as the expression condition remains true
(evaluates to a non‐zero value)
11
while Loops (continued)
12
Loop repeated 10 times
Start value 1
End value 10
Increment 1
Last value of count is 11
while Loops (Examples)
13
Loop repeated 5 times
Start value 0
End value 20
Increment 5
Last value of i is 25
while Loops (Examples)
14
Loop repeated 0 times
Start value 20
End value N/A
Increment 5
Last value of i is 20
Counter‐Controlled while Loops
• Suppose that a set of statements needs to be executed N
times
• You can set up a counter (initialized to 0 before the while
statement) to track how many items have passed
15
Counter‐Controlled while Loops
16
Loop repeated limit times
Start value 0
End value limit ‐1
Increment 1
Last value of counter is limit
Counter‐Controlled while Loops
17
Counter‐Controlled while Loops
18
while Loops with Sentinels
• Sentinel: A data value used to signal either the start
or end of a data series
• Use a sentinel when you don’t know how many values
need to be entered (looping is controlled by the user)
19
while Loops with Sentinels
20
while Loops with Sentinels
21
while Loops with Sentinels
22
Flag‐Controlled while Loops
• A flag‐controlled while loop uses a bool variable to control
the loop.
• Suppose found is a bool variable. The flag‐controlled while
loop takes the following form:
23
• break statement
– Forces an immediate break, or exit, from
switch, while, for, and do-while
statements
– Violates pure structured programming, but is
useful for breaking out of loops when an unusual
condition is detected
break and continue Statements
24
• Example of a break statement:
break and continue Statements
(cont’d)
25
• continue statement
– Applies to while, do-while, and for statements;
causes the next iteration of the loop to begin
immediately
– Useful for skipping over data that should not be
processed in this iteration, while staying within the
loop
break and continue Statements
(cont’d)
26
• A continue statement where invalid grades are
ignored, and only valid grades are added to the total:
break and continue Statements
(cont’d)
27
• Null statement
– Semicolon with nothing preceding it
• ;
– Do‐nothing statement required for syntax purposes only
The Null Statement
28
for Loops
• for statement: A loop with a fixed count condition
that handles alteration of the condition
– Syntax:
for(initializing list; expression; altering list)
statement;
• Initializing list: Sets the starting value of a counter
• Expression: Contains the maximum or minimum value
the counter can have; determines when the loop is
finished
29
for Loops
30
Loop repeated 10 times
Start value 0
End value 9
Increment 1
Last value of i is 10
Note: Only this statement is executed with
the loop since there is no curled brackets.
• Altering list: Provides the increment value that is
added or subtracted from the counter in each
iteration of the loop
• If initializing list is missing, the counter initial value
must be provided prior to entering the for loop
• If altering list is missing, the counter must be altered
in the loop body
• Omitting the expression will result in an infinite loop
for Loops (continued)
31
for Loops (continued)
32
for loop
flowchart.
for Loops (cont’d)
33
for Loops (Examples)
34
for Loops (Examples)
35
for Loops (Examples)
36
• These techniques are suitable for pretest loops ( for
and while):
– Interactive input within a loop
• Includes a cin statement within a while or for loop
– Selection within a loop
• Using a for or while loop to cycle through a set of
values to select those values that meet some criteria
A Closer Look: Loop Programming
Techniques
37
A Closer Look: Loop Programming
Techniques (continued)
38
A Closer Look: Loop Programming
Techniques (continued)
39
A Closer Look: Loop Programming
Techniques (continued)
40
• Nested loop: A loop contained within another loop
– All statements of the inner loop must be completely
contained within the outer loop; no overlap allowed
– Different variables must be used to control each loop
– For each single iteration of the outer loop, the inner loop
runs through all of its iterations
Nested Loops
41
Nested Loops (continued)
For each i, j loops.
42
Nested Loops (continued)
43
• do while loop is a posttest loop
– Loop continues while the condition is true
– Condition is tested at the end of the loop
– Syntax:
do
statement;
while (expression);
• All statements are executed at least once in a
posttest loop
do while Loops
44
The do while
loop structure.
do while Loops
45
The do
statement’s
flow of control.
do while Loops
46
do while Loops (Examples)
47
Loop repeated 5 times
Start value 0
End value 25
Increment 5
Last value of counter is 25
• Useful in filtering user‐entered input and providing
data validation checks
• Can enhance with if-else statement
Validity Checks
48
• Using the assignment operator (=) instead of the equality
comparison operator (==) in the condition expression
• Placing a semicolon at the end of the for clause, which
produces a null loop body
• Using commas instead of semicolons to separate items in
the for statement
• Changing the value of the control variable
• Omitting the final semicolon in a do statement
Common Programming Errors
49
Summary
• Loop: A section of repeating code, whose
repetitions are controlled by testing a condition
• Three types of loops:
– while
– for
– do while
• Pretest loop: Condition is tested at beginning of
loop; loop body may not ever execute; ex., while,
for loops
50
Summary (continued)
• Posttest loop: Condition is tested at end of loop;
loop body executes at least once; ex., do while
• Fixed‐count loop: Number of repetitions is set in
the loop condition
• Variable‐condition loop: Number of repetitions is
controlled by the value of a variable
51

More Related Content

What's hot (11)

DDL And DML
DDL And DMLDDL And DML
DDL And DML
pnp @in
 
Formal Methods lecture 01
Formal Methods lecture 01Formal Methods lecture 01
Formal Methods lecture 01
Sidra Ashraf
 
System testing ppt
System testing pptSystem testing ppt
System testing ppt
L ESHWAR
 
Basic computer skill training free for anyone.pptx
Basic computer skill training free for anyone.pptxBasic computer skill training free for anyone.pptx
Basic computer skill training free for anyone.pptx
ReshidJewar
 
software testing
 software testing software testing
software testing
Sara shall
 
Software Testing - Software Quality (Part 2)
Software Testing - Software Quality (Part 2)Software Testing - Software Quality (Part 2)
Software Testing - Software Quality (Part 2)
Ajeng Savitri
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
Mark John Lado, MIT
 
Using Computer Keyboard
Using Computer KeyboardUsing Computer Keyboard
Using Computer Keyboard
Globelle Dala-Pasamante
 
Intro To Scratch
Intro To ScratchIntro To Scratch
Intro To Scratch
Patrick Woessner
 
개발자, 성장하는 '척' 말고, 진짜 성장하기
개발자, 성장하는 '척' 말고, 진짜 성장하기개발자, 성장하는 '척' 말고, 진짜 성장하기
개발자, 성장하는 '척' 말고, 진짜 성장하기
Donghyun Cho
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
Abhishek Soni
 
DDL And DML
DDL And DMLDDL And DML
DDL And DML
pnp @in
 
Formal Methods lecture 01
Formal Methods lecture 01Formal Methods lecture 01
Formal Methods lecture 01
Sidra Ashraf
 
System testing ppt
System testing pptSystem testing ppt
System testing ppt
L ESHWAR
 
Basic computer skill training free for anyone.pptx
Basic computer skill training free for anyone.pptxBasic computer skill training free for anyone.pptx
Basic computer skill training free for anyone.pptx
ReshidJewar
 
software testing
 software testing software testing
software testing
Sara shall
 
Software Testing - Software Quality (Part 2)
Software Testing - Software Quality (Part 2)Software Testing - Software Quality (Part 2)
Software Testing - Software Quality (Part 2)
Ajeng Savitri
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
Mark John Lado, MIT
 
개발자, 성장하는 '척' 말고, 진짜 성장하기
개발자, 성장하는 '척' 말고, 진짜 성장하기개발자, 성장하는 '척' 말고, 진짜 성장하기
개발자, 성장하는 '척' 말고, 진짜 성장하기
Donghyun Cho
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
Abhishek Soni
 

Similar to Repetition, Basic loop structures, Loop programming techniques (20)

Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
Sowmya Jyothi
 
Looping statements
Looping statementsLooping statements
Looping statements
AbhishekMondal42
 
Programming loop
Programming loopProgramming loop
Programming loop
University of Potsdam
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Introduction to Java Programming - Lecture 11.pptx
Introduction to Java Programming - Lecture 11.pptxIntroduction to Java Programming - Lecture 11.pptx
Introduction to Java Programming - Lecture 11.pptx
AbdulKhaleqHerawi1
 
Chapter 12 Computer Science ( ICS 12).pdf
Chapter 12 Computer Science ( ICS 12).pdfChapter 12 Computer Science ( ICS 12).pdf
Chapter 12 Computer Science ( ICS 12).pdf
AamirShahzad527024
 
for loops in C++ and their functions and applicability
for loops in C++ and their functions and applicabilityfor loops in C++ and their functions and applicability
for loops in C++ and their functions and applicability
ayeshaaaliasad
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flow
Pushpa Yakkala
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
Dr. SURBHI SAROHA
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
Vladislav Hadzhiyski
 
Looping statements
Looping statementsLooping statements
Looping statements
Marco Alzamora
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
sanjay
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
chapter 6.pptx
chapter 6.pptxchapter 6.pptx
chapter 6.pptx
ThedronBerhanu
 
Decision making and looping
Decision making and loopingDecision making and looping
Decision making and looping
Hossain Md Shakhawat
 
Lecture 6.2 flow control repetition
Lecture 6.2  flow control repetitionLecture 6.2  flow control repetition
Lecture 6.2 flow control repetition
alvin567
 
Control structure
Control structureControl structure
Control structure
Samsil Arefin
 
ch5.ppt
ch5.pptch5.ppt
ch5.ppt
ssusere004a8
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
Sowmya Jyothi
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Introduction to Java Programming - Lecture 11.pptx
Introduction to Java Programming - Lecture 11.pptxIntroduction to Java Programming - Lecture 11.pptx
Introduction to Java Programming - Lecture 11.pptx
AbdulKhaleqHerawi1
 
Chapter 12 Computer Science ( ICS 12).pdf
Chapter 12 Computer Science ( ICS 12).pdfChapter 12 Computer Science ( ICS 12).pdf
Chapter 12 Computer Science ( ICS 12).pdf
AamirShahzad527024
 
for loops in C++ and their functions and applicability
for loops in C++ and their functions and applicabilityfor loops in C++ and their functions and applicability
for loops in C++ and their functions and applicability
ayeshaaaliasad
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flow
Pushpa Yakkala
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
Vladislav Hadzhiyski
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
sanjay
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
Lecture 6.2 flow control repetition
Lecture 6.2  flow control repetitionLecture 6.2  flow control repetition
Lecture 6.2 flow control repetition
alvin567
 
Ad

More from Jason J Pulikkottil (20)

Unix/Linux Command Reference - File Commands and Shortcuts
Unix/Linux Command Reference - File Commands and ShortcutsUnix/Linux Command Reference - File Commands and Shortcuts
Unix/Linux Command Reference - File Commands and Shortcuts
Jason J Pulikkottil
 
Introduction to PERL Programming - Complete Notes
Introduction to PERL Programming - Complete NotesIntroduction to PERL Programming - Complete Notes
Introduction to PERL Programming - Complete Notes
Jason J Pulikkottil
 
VLSI System Verilog Notes with Coding Examples
VLSI System Verilog Notes with Coding ExamplesVLSI System Verilog Notes with Coding Examples
VLSI System Verilog Notes with Coding Examples
Jason J Pulikkottil
 
VLSI Physical Design Physical Design Concepts
VLSI Physical Design Physical Design ConceptsVLSI Physical Design Physical Design Concepts
VLSI Physical Design Physical Design Concepts
Jason J Pulikkottil
 
Verilog Coding examples of Digital Circuits
Verilog Coding examples of Digital CircuitsVerilog Coding examples of Digital Circuits
Verilog Coding examples of Digital Circuits
Jason J Pulikkottil
 
Floor Plan, Placement Questions and Answers
Floor Plan, Placement Questions and AnswersFloor Plan, Placement Questions and Answers
Floor Plan, Placement Questions and Answers
Jason J Pulikkottil
 
Physical Design, ASIC Design, Standard Cells
Physical Design, ASIC Design, Standard CellsPhysical Design, ASIC Design, Standard Cells
Physical Design, ASIC Design, Standard Cells
Jason J Pulikkottil
 
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Basic Electronics, Digital Electronics, Static Timing Analysis NotesBasic Electronics, Digital Electronics, Static Timing Analysis Notes
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Jason J Pulikkottil
 
Floorplan, Powerplan and Data Setup, Stages
Floorplan, Powerplan and Data Setup, StagesFloorplan, Powerplan and Data Setup, Stages
Floorplan, Powerplan and Data Setup, Stages
Jason J Pulikkottil
 
Floorplanning Power Planning and Placement
Floorplanning Power Planning and PlacementFloorplanning Power Planning and Placement
Floorplanning Power Planning and Placement
Jason J Pulikkottil
 
Digital Electronics Questions and Answers
Digital Electronics Questions and AnswersDigital Electronics Questions and Answers
Digital Electronics Questions and Answers
Jason J Pulikkottil
 
Different Types Of Cells, Types of Standard Cells
Different Types Of Cells, Types of Standard CellsDifferent Types Of Cells, Types of Standard Cells
Different Types Of Cells, Types of Standard Cells
Jason J Pulikkottil
 
DFT Rules, set of rules with illustration
DFT Rules, set of rules with illustrationDFT Rules, set of rules with illustration
DFT Rules, set of rules with illustration
Jason J Pulikkottil
 
Clock Definitions Static Timing Analysis for VLSI Engineers
Clock Definitions Static Timing Analysis for VLSI EngineersClock Definitions Static Timing Analysis for VLSI Engineers
Clock Definitions Static Timing Analysis for VLSI Engineers
Jason J Pulikkottil
 
Basic Synthesis Flow and Commands, Logic Synthesis
Basic Synthesis Flow and Commands, Logic SynthesisBasic Synthesis Flow and Commands, Logic Synthesis
Basic Synthesis Flow and Commands, Logic Synthesis
Jason J Pulikkottil
 
ASIC Design Types, Logical Libraries, Optimization
ASIC Design Types, Logical Libraries, OptimizationASIC Design Types, Logical Libraries, Optimization
ASIC Design Types, Logical Libraries, Optimization
Jason J Pulikkottil
 
Floorplanning and Powerplanning - Definitions and Notes
Floorplanning and Powerplanning - Definitions and NotesFloorplanning and Powerplanning - Definitions and Notes
Floorplanning and Powerplanning - Definitions and Notes
Jason J Pulikkottil
 
Physical Design Flow - Standard Cells and Special Cells
Physical Design Flow - Standard Cells and Special CellsPhysical Design Flow - Standard Cells and Special Cells
Physical Design Flow - Standard Cells and Special Cells
Jason J Pulikkottil
 
Physical Design - Import Design Flow Floorplan
Physical Design - Import Design Flow FloorplanPhysical Design - Import Design Flow Floorplan
Physical Design - Import Design Flow Floorplan
Jason J Pulikkottil
 
Physical Design-Floor Planning Goals And Placement
Physical Design-Floor Planning Goals And PlacementPhysical Design-Floor Planning Goals And Placement
Physical Design-Floor Planning Goals And Placement
Jason J Pulikkottil
 
Unix/Linux Command Reference - File Commands and Shortcuts
Unix/Linux Command Reference - File Commands and ShortcutsUnix/Linux Command Reference - File Commands and Shortcuts
Unix/Linux Command Reference - File Commands and Shortcuts
Jason J Pulikkottil
 
Introduction to PERL Programming - Complete Notes
Introduction to PERL Programming - Complete NotesIntroduction to PERL Programming - Complete Notes
Introduction to PERL Programming - Complete Notes
Jason J Pulikkottil
 
VLSI System Verilog Notes with Coding Examples
VLSI System Verilog Notes with Coding ExamplesVLSI System Verilog Notes with Coding Examples
VLSI System Verilog Notes with Coding Examples
Jason J Pulikkottil
 
VLSI Physical Design Physical Design Concepts
VLSI Physical Design Physical Design ConceptsVLSI Physical Design Physical Design Concepts
VLSI Physical Design Physical Design Concepts
Jason J Pulikkottil
 
Verilog Coding examples of Digital Circuits
Verilog Coding examples of Digital CircuitsVerilog Coding examples of Digital Circuits
Verilog Coding examples of Digital Circuits
Jason J Pulikkottil
 
Floor Plan, Placement Questions and Answers
Floor Plan, Placement Questions and AnswersFloor Plan, Placement Questions and Answers
Floor Plan, Placement Questions and Answers
Jason J Pulikkottil
 
Physical Design, ASIC Design, Standard Cells
Physical Design, ASIC Design, Standard CellsPhysical Design, ASIC Design, Standard Cells
Physical Design, ASIC Design, Standard Cells
Jason J Pulikkottil
 
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Basic Electronics, Digital Electronics, Static Timing Analysis NotesBasic Electronics, Digital Electronics, Static Timing Analysis Notes
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Jason J Pulikkottil
 
Floorplan, Powerplan and Data Setup, Stages
Floorplan, Powerplan and Data Setup, StagesFloorplan, Powerplan and Data Setup, Stages
Floorplan, Powerplan and Data Setup, Stages
Jason J Pulikkottil
 
Floorplanning Power Planning and Placement
Floorplanning Power Planning and PlacementFloorplanning Power Planning and Placement
Floorplanning Power Planning and Placement
Jason J Pulikkottil
 
Digital Electronics Questions and Answers
Digital Electronics Questions and AnswersDigital Electronics Questions and Answers
Digital Electronics Questions and Answers
Jason J Pulikkottil
 
Different Types Of Cells, Types of Standard Cells
Different Types Of Cells, Types of Standard CellsDifferent Types Of Cells, Types of Standard Cells
Different Types Of Cells, Types of Standard Cells
Jason J Pulikkottil
 
DFT Rules, set of rules with illustration
DFT Rules, set of rules with illustrationDFT Rules, set of rules with illustration
DFT Rules, set of rules with illustration
Jason J Pulikkottil
 
Clock Definitions Static Timing Analysis for VLSI Engineers
Clock Definitions Static Timing Analysis for VLSI EngineersClock Definitions Static Timing Analysis for VLSI Engineers
Clock Definitions Static Timing Analysis for VLSI Engineers
Jason J Pulikkottil
 
Basic Synthesis Flow and Commands, Logic Synthesis
Basic Synthesis Flow and Commands, Logic SynthesisBasic Synthesis Flow and Commands, Logic Synthesis
Basic Synthesis Flow and Commands, Logic Synthesis
Jason J Pulikkottil
 
ASIC Design Types, Logical Libraries, Optimization
ASIC Design Types, Logical Libraries, OptimizationASIC Design Types, Logical Libraries, Optimization
ASIC Design Types, Logical Libraries, Optimization
Jason J Pulikkottil
 
Floorplanning and Powerplanning - Definitions and Notes
Floorplanning and Powerplanning - Definitions and NotesFloorplanning and Powerplanning - Definitions and Notes
Floorplanning and Powerplanning - Definitions and Notes
Jason J Pulikkottil
 
Physical Design Flow - Standard Cells and Special Cells
Physical Design Flow - Standard Cells and Special CellsPhysical Design Flow - Standard Cells and Special Cells
Physical Design Flow - Standard Cells and Special Cells
Jason J Pulikkottil
 
Physical Design - Import Design Flow Floorplan
Physical Design - Import Design Flow FloorplanPhysical Design - Import Design Flow Floorplan
Physical Design - Import Design Flow Floorplan
Jason J Pulikkottil
 
Physical Design-Floor Planning Goals And Placement
Physical Design-Floor Planning Goals And PlacementPhysical Design-Floor Planning Goals And Placement
Physical Design-Floor Planning Goals And Placement
Jason J Pulikkottil
 
Ad

Recently uploaded (20)

362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdfOCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Blood bank management system project report.pdf
Blood bank management system project report.pdfBlood bank management system project report.pdf
Blood bank management system project report.pdf
Kamal Acharya
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdfOCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Blood bank management system project report.pdf
Blood bank management system project report.pdfBlood bank management system project report.pdf
Blood bank management system project report.pdf
Kamal Acharya
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 

Repetition, Basic loop structures, Loop programming techniques

  • 1. Introduction to Computer Programming Control Structures – Repetition C++ Programming: From Problem Analysis to Program Design 1
  • 2. • Basic loop structures • while loops • Interactive while loops • for loops • Loop programming techniques • Nested loops • do whileloops • Common programming errors Chapter Topics 2
  • 3. • Suppose you want to add five numbers to find their average. From what you have learned so far, you could proceed as follows: • Assume that all variables are properly declared Why Is Repetition Needed? 3
  • 4. Why Is Repetition Needed? • Suppose you want to add and average 100, 1000, or more numbers – You would have to declare that many variables – List them again in cin statements • This takes an exorbitant amount of space and time • Also, if you want to run this program again with different values or with a different number of values, you have to rewrite the program 4
  • 5. • Suppose you want to add the following numbers: 5 3 7 9 4 • Consider the following statements, in which sum and num are variables of type int: 1. sum = 0; 2. cin >> num; 3. sum = sum + num; • Each time you need to add a new number, you repeat statements 2 and 3 Why Is Repetition Needed? 5
  • 6. • Repetition structure has four required elements: – Repetition statement – Condition to be evaluated – Initial value for the condition – Loop termination • Repetition statements include: – while – for – do while Basic Loop Structures 6 f o r ( i = 0 ; i < 1 0 ; i + + ) c o u t < < i ;
  • 7. • The condition can be tested – At the beginning: Pretest or entrance‐controlled loop (while, for) – At the end: Posttest or exit‐controlled loop (do‐while) • Something in the loop body must cause the condition to change, to avoid an infinite loop, which never terminates Basic Loop Structures (continued) 7
  • 8. • Pretest loop: Condition is tested first; if false, statements in the loop body are never executed • while and for loops are pretest loops Pretest and Posttest Loops A pretest loop 8
  • 9. Pretest and Posttest Loops (continued) • Posttest loop: Condition is tested after the loop body statements are executed; loop body always executes at least once • do while is a posttest loop A posttest loop 9
  • 10. • Fixed‐count loop: Loop is processed for a fixed number of repetitions • Variable‐condition loop: Number of repetitions depends on the value of a variable Fixed‐Count Versus Variable‐Condition Loops 10 f o r ( i = 0 ; i < 1 0 ; i + + ) c o u t < < i ; f o r ( i = 0 ; i < a ; i + + ) c o u t < < i ;
  • 11. while Loops • while statement is used to create a while loop – Syntax: while (expression) statement; • Statements following the expressions are executed as long as the expression condition remains true (evaluates to a non‐zero value) 11
  • 12. while Loops (continued) 12 Loop repeated 10 times Start value 1 End value 10 Increment 1 Last value of count is 11
  • 13. while Loops (Examples) 13 Loop repeated 5 times Start value 0 End value 20 Increment 5 Last value of i is 25
  • 14. while Loops (Examples) 14 Loop repeated 0 times Start value 20 End value N/A Increment 5 Last value of i is 20
  • 15. Counter‐Controlled while Loops • Suppose that a set of statements needs to be executed N times • You can set up a counter (initialized to 0 before the while statement) to track how many items have passed 15
  • 16. Counter‐Controlled while Loops 16 Loop repeated limit times Start value 0 End value limit ‐1 Increment 1 Last value of counter is limit
  • 19. while Loops with Sentinels • Sentinel: A data value used to signal either the start or end of a data series • Use a sentinel when you don’t know how many values need to be entered (looping is controlled by the user) 19
  • 20. while Loops with Sentinels 20
  • 21. while Loops with Sentinels 21
  • 22. while Loops with Sentinels 22
  • 23. Flag‐Controlled while Loops • A flag‐controlled while loop uses a bool variable to control the loop. • Suppose found is a bool variable. The flag‐controlled while loop takes the following form: 23
  • 24. • break statement – Forces an immediate break, or exit, from switch, while, for, and do-while statements – Violates pure structured programming, but is useful for breaking out of loops when an unusual condition is detected break and continue Statements 24
  • 25. • Example of a break statement: break and continue Statements (cont’d) 25
  • 26. • continue statement – Applies to while, do-while, and for statements; causes the next iteration of the loop to begin immediately – Useful for skipping over data that should not be processed in this iteration, while staying within the loop break and continue Statements (cont’d) 26
  • 27. • A continue statement where invalid grades are ignored, and only valid grades are added to the total: break and continue Statements (cont’d) 27
  • 28. • Null statement – Semicolon with nothing preceding it • ; – Do‐nothing statement required for syntax purposes only The Null Statement 28
  • 29. for Loops • for statement: A loop with a fixed count condition that handles alteration of the condition – Syntax: for(initializing list; expression; altering list) statement; • Initializing list: Sets the starting value of a counter • Expression: Contains the maximum or minimum value the counter can have; determines when the loop is finished 29
  • 30. for Loops 30 Loop repeated 10 times Start value 0 End value 9 Increment 1 Last value of i is 10 Note: Only this statement is executed with the loop since there is no curled brackets.
  • 31. • Altering list: Provides the increment value that is added or subtracted from the counter in each iteration of the loop • If initializing list is missing, the counter initial value must be provided prior to entering the for loop • If altering list is missing, the counter must be altered in the loop body • Omitting the expression will result in an infinite loop for Loops (continued) 31
  • 37. • These techniques are suitable for pretest loops ( for and while): – Interactive input within a loop • Includes a cin statement within a while or for loop – Selection within a loop • Using a for or while loop to cycle through a set of values to select those values that meet some criteria A Closer Look: Loop Programming Techniques 37
  • 38. A Closer Look: Loop Programming Techniques (continued) 38
  • 39. A Closer Look: Loop Programming Techniques (continued) 39
  • 40. A Closer Look: Loop Programming Techniques (continued) 40
  • 41. • Nested loop: A loop contained within another loop – All statements of the inner loop must be completely contained within the outer loop; no overlap allowed – Different variables must be used to control each loop – For each single iteration of the outer loop, the inner loop runs through all of its iterations Nested Loops 41
  • 42. Nested Loops (continued) For each i, j loops. 42
  • 44. • do while loop is a posttest loop – Loop continues while the condition is true – Condition is tested at the end of the loop – Syntax: do statement; while (expression); • All statements are executed at least once in a posttest loop do while Loops 44
  • 45. The do while loop structure. do while Loops 45
  • 46. The do statement’s flow of control. do while Loops 46
  • 47. do while Loops (Examples) 47 Loop repeated 5 times Start value 0 End value 25 Increment 5 Last value of counter is 25
  • 48. • Useful in filtering user‐entered input and providing data validation checks • Can enhance with if-else statement Validity Checks 48
  • 49. • Using the assignment operator (=) instead of the equality comparison operator (==) in the condition expression • Placing a semicolon at the end of the for clause, which produces a null loop body • Using commas instead of semicolons to separate items in the for statement • Changing the value of the control variable • Omitting the final semicolon in a do statement Common Programming Errors 49
  • 50. Summary • Loop: A section of repeating code, whose repetitions are controlled by testing a condition • Three types of loops: – while – for – do while • Pretest loop: Condition is tested at beginning of loop; loop body may not ever execute; ex., while, for loops 50
  • 51. Summary (continued) • Posttest loop: Condition is tested at end of loop; loop body executes at least once; ex., do while • Fixed‐count loop: Number of repetitions is set in the loop condition • Variable‐condition loop: Number of repetitions is controlled by the value of a variable 51