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 (20)

PPT
Risc and cisc eugene clewlow
karan saini
 
PPTX
Core 2 Duo Processor
Kashif Latif
 
PDF
Syntax Directed Definitions Synthesized Attributes and Inherited Attributes
GunjalSanjay
 
PPTX
Computer architecture control unit
Mazin Alwaaly
 
PPT
Unit 1 python (2021 r)
praveena p
 
PDF
ARM CORTEX M3 PPT
Gaurav Verma
 
PDF
Bit pair recoding
Basit Ali
 
PPT
Stored program concept
gaurav jain
 
PPTX
1 Computer Architecture
fika sweety
 
PPT
The Electric Circuit And Kirchhoff’S Rules by Students
kulachihansraj
 
PPTX
Introduction to system programming
sonalikharade3
 
PPTX
Bcd
Talha Fazal
 
PDF
7BCEE2A - UNIT V - STACK ORGANIZATION.pdf
RajendranSheeba
 
PPTX
Memory interfacing
mahalakshmimalini
 
PPTX
instruction cycle ppt
sheetal singh
 
PPTX
Addressing Modes.pptx
AshokRachapalli1
 
PPTX
Addressing Modes
Mayank Garg
 
PPTX
Variables, Data Types, Operator & Expression in c in detail
gourav kottawar
 
PPT
control-statements, control-statements, control statement
crrpavankumar
 
Risc and cisc eugene clewlow
karan saini
 
Core 2 Duo Processor
Kashif Latif
 
Syntax Directed Definitions Synthesized Attributes and Inherited Attributes
GunjalSanjay
 
Computer architecture control unit
Mazin Alwaaly
 
Unit 1 python (2021 r)
praveena p
 
ARM CORTEX M3 PPT
Gaurav Verma
 
Bit pair recoding
Basit Ali
 
Stored program concept
gaurav jain
 
1 Computer Architecture
fika sweety
 
The Electric Circuit And Kirchhoff’S Rules by Students
kulachihansraj
 
Introduction to system programming
sonalikharade3
 
7BCEE2A - UNIT V - STACK ORGANIZATION.pdf
RajendranSheeba
 
Memory interfacing
mahalakshmimalini
 
instruction cycle ppt
sheetal singh
 
Addressing Modes.pptx
AshokRachapalli1
 
Addressing Modes
Mayank Garg
 
Variables, Data Types, Operator & Expression in c in detail
gourav kottawar
 
control-statements, control-statements, control statement
crrpavankumar
 

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

PPTX
Loops c++
Shivani Singh
 
PPT
Loops
abdulmanan366
 
PPTX
Loops in c programming
CHANDAN KUMAR
 
PDF
Chapter 3 - Flow of Control Part II.pdf
KirubelWondwoson1
 
PPT
Iteration
Liam Dunphy
 
DOCX
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
PPSX
C lecture 3 control statements slideshare
Gagan Deep
 
PDF
Lecture15 comparisonoftheloopcontrolstructures.ppt
eShikshak
 
PPT
Chapter06.PPT
vamsiKrishnasai3
 
PPT
Loops Do While Arduino Programming Robotics
JhaeZaSangcapGarrido
 
PPT
Mesics lecture 7 iteration and repetitive executions
eShikshak
 
PPT
Fundamentals of Programming Chapter 7
Mohd Harris Ahmad Jaal
 
PPT
04a intro while
hasfaa1017
 
PDF
Loops
Learn By Watch
 
PPT
Control structures repetition
Online
 
PPTX
The Loops
Krishma Parekh
 
PPTX
Introduction to Repetition Structures
primeteacher32
 
PDF
04-Looping( For , while and do while looping) .pdf
nithishkumar2867
 
PPT
Conditional Loops Python
primeteacher32
 
Loops c++
Shivani Singh
 
Loops in c programming
CHANDAN KUMAR
 
Chapter 3 - Flow of Control Part II.pdf
KirubelWondwoson1
 
Iteration
Liam Dunphy
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
C lecture 3 control statements slideshare
Gagan Deep
 
Lecture15 comparisonoftheloopcontrolstructures.ppt
eShikshak
 
Chapter06.PPT
vamsiKrishnasai3
 
Loops Do While Arduino Programming Robotics
JhaeZaSangcapGarrido
 
Mesics lecture 7 iteration and repetitive executions
eShikshak
 
Fundamentals of Programming Chapter 7
Mohd Harris Ahmad Jaal
 
04a intro while
hasfaa1017
 
Control structures repetition
Online
 
The Loops
Krishma Parekh
 
Introduction to Repetition Structures
primeteacher32
 
04-Looping( For , while and do while looping) .pdf
nithishkumar2867
 
Conditional Loops Python
primeteacher32
 
Ad

More from Jason J Pulikkottil (20)

PDF
Unix/Linux Command Reference - File Commands and Shortcuts
Jason J Pulikkottil
 
PDF
Introduction to PERL Programming - Complete Notes
Jason J Pulikkottil
 
PDF
VLSI System Verilog Notes with Coding Examples
Jason J Pulikkottil
 
PDF
VLSI Physical Design Physical Design Concepts
Jason J Pulikkottil
 
PDF
Verilog Coding examples of Digital Circuits
Jason J Pulikkottil
 
PDF
Floor Plan, Placement Questions and Answers
Jason J Pulikkottil
 
PDF
Physical Design, ASIC Design, Standard Cells
Jason J Pulikkottil
 
PDF
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Jason J Pulikkottil
 
PDF
Floorplan, Powerplan and Data Setup, Stages
Jason J Pulikkottil
 
PDF
Floorplanning Power Planning and Placement
Jason J Pulikkottil
 
PDF
Digital Electronics Questions and Answers
Jason J Pulikkottil
 
PDF
Different Types Of Cells, Types of Standard Cells
Jason J Pulikkottil
 
PDF
DFT Rules, set of rules with illustration
Jason J Pulikkottil
 
PDF
Clock Definitions Static Timing Analysis for VLSI Engineers
Jason J Pulikkottil
 
PDF
Basic Synthesis Flow and Commands, Logic Synthesis
Jason J Pulikkottil
 
PDF
ASIC Design Types, Logical Libraries, Optimization
Jason J Pulikkottil
 
PDF
Floorplanning and Powerplanning - Definitions and Notes
Jason J Pulikkottil
 
PDF
Physical Design Flow - Standard Cells and Special Cells
Jason J Pulikkottil
 
PDF
Physical Design - Import Design Flow Floorplan
Jason J Pulikkottil
 
PDF
Physical Design-Floor Planning Goals And Placement
Jason J Pulikkottil
 
Unix/Linux Command Reference - File Commands and Shortcuts
Jason J Pulikkottil
 
Introduction to PERL Programming - Complete Notes
Jason J Pulikkottil
 
VLSI System Verilog Notes with Coding Examples
Jason J Pulikkottil
 
VLSI Physical Design Physical Design Concepts
Jason J Pulikkottil
 
Verilog Coding examples of Digital Circuits
Jason J Pulikkottil
 
Floor Plan, Placement Questions and Answers
Jason J Pulikkottil
 
Physical Design, ASIC Design, Standard Cells
Jason J Pulikkottil
 
Basic Electronics, Digital Electronics, Static Timing Analysis Notes
Jason J Pulikkottil
 
Floorplan, Powerplan and Data Setup, Stages
Jason J Pulikkottil
 
Floorplanning Power Planning and Placement
Jason J Pulikkottil
 
Digital Electronics Questions and Answers
Jason J Pulikkottil
 
Different Types Of Cells, Types of Standard Cells
Jason J Pulikkottil
 
DFT Rules, set of rules with illustration
Jason J Pulikkottil
 
Clock Definitions Static Timing Analysis for VLSI Engineers
Jason J Pulikkottil
 
Basic Synthesis Flow and Commands, Logic Synthesis
Jason J Pulikkottil
 
ASIC Design Types, Logical Libraries, Optimization
Jason J Pulikkottil
 
Floorplanning and Powerplanning - Definitions and Notes
Jason J Pulikkottil
 
Physical Design Flow - Standard Cells and Special Cells
Jason J Pulikkottil
 
Physical Design - Import Design Flow Floorplan
Jason J Pulikkottil
 
Physical Design-Floor Planning Goals And Placement
Jason J Pulikkottil
 
Ad

Recently uploaded (20)

PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 

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