SlideShare une entreprise Scribd logo
1  sur  19
Lecture #04:

Loops
C# Control Structures: Repetition
for structure/foreach structure

while structure
T
F

T
do/while structure

F

T
F

2
while Statement
The while statement has the following
syntax:
while is a
reserved word

If the condition is true, the statement is executed.
Then the condition is evaluated again.
while ( condition )
statement;

The statement (or a block of statements) is executed
repetitively until the condition becomes false.

3
while Statement (cont’d)

true
Product <= 1000

Product = 2 * product

false
int product;
product = 2;
while (product <= 1000)
{
product = 2 * product;
}
// beginning of the next statement
4
while Statement
Note that if the condition of a while statement
is false initially, the statement is never
executed
Therefore, the body of a while loop will
execute zero or more times

5
Infinite Loops
The body of a while loop must eventually make the
condition false
If not, it is an infinite loop, which will execute until the
user interrupts the program
This is a common type of logical error
You should always double check to ensure that your
loops will terminate normally

6
Example 1: Counter Controlled While Loop
Control variable
• The variable used as a counter to determine whether or
not the loop should continue

Three components
• Initial value of the counter
• Check whether or not the counter has reached target
– When the looping should continue
• Incrementing/decrementing of the counter

7
Example 2: Sentinel Controlled while Loops
This is typical of an input-driven program
Continues an arbitrary amount of times
Sentinel value
• Causes loop to break
• Avoid collisions
– When flag value = user entered value

8
The do Statement
The do statement has the following syntax:
Uses both
the do and
while
reserved
words

do
{
statement;
}
while ( condition );

The statement is executed once initially, then the condition is evaluated
The statement is repetitively executed until the condition becomes false

9
do/while Flowchart

action(s)

true
condition
false

Fig. 5.13 Flowcharting the do/while repetition structure.
10
Comparing the while and do Loops
The while loops vs. the do/while loops
Using a while loop
• Condition is tested
• The action is performed
• Loop could be skipped altogether

while structure
T
F
do/while structure

Using a do/while loop
• Action is performed
• Then the loop condition is tested
• Loop will be run at least once

T
F

Question: write a program to get max from user and then print the numbers from 1 to max
11
The for Statement
The for statement has the following syntax:
Reserved
word

The initialization portion
is executed once
before the loop begins

The statement is
executed until the
condition becomes false

for ( initialization ; condition ; increment )
statement;

The increment portion is executed at the end of each iteration

12
Flowchart of a for loop
initialization

condition

true

action(s)

increment

false

for ( initialization ; condition ; increment )
action(s);
13
The for Statement: Example
Establish initial value
of control variable.

Determine if final
value of control
variable has
been reached.

int counter = 1

counter <= 10

false

true Console.WriteLine
( counter * 10 );
Body of loop (this may
be multiple statements)

counter++
Increment the
control variable.

for (int counter = 1; counter <= 10; counter++)
Console.WriteLine (counter * 10);

// beginning of the next statement
14
The for Statement
A for loop is equivalent to the following
while loop:
initialization;
while ( condition )
{
statement;
increment;
}

15
The for Statement
It is well suited for executing a specific
number of times that can be determined in
advance
Increment/Decrement
• When incrementing
– In most cases < or <= is used
• When decrementing
– In most cases > or >= is used

16
The flexibility of the for Statement
Each expression in the header of a for loop is optional
If the initialization is left out, no initialization is performed
If the condition is left out, it is always considered to be true,
and therefore creates an infinite loop
If the increment is left out, no increment operation is performed

Both semi-colons are always required in the for loop
header

for ( ; ; )
{
// do something
}
17
A Problem to Think About
How to print this?
xxxxxxxx
xxxxxxx
xxxxxx
xxxxx
xxxx
xxx
xx
x

What about this?
xxxxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxx
xxxxxxx
xxxxx
xxx
x
18
Statements break and continue
Used to alter the flow of control
The break statement
• Used to exit a loop early

The continue statement
• Used to skip the rest of the statements in a loop and
restart at the first statement in the loop

Programs can be completed without their
usage; use with caution.
19

Contenu connexe

Tendances

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in cvampugani
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Mesics lecture 6 control statement = if -else if__else
Mesics lecture 6   control statement = if -else if__elseMesics lecture 6   control statement = if -else if__else
Mesics lecture 6 control statement = if -else if__elseeShikshak
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c languagesneha2494
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopPriyom Majumder
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 

Tendances (20)

Control statement in c
Control statement in cControl statement in c
Control statement in c
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Mesics lecture 6 control statement = if -else if__else
Mesics lecture 6   control statement = if -else if__elseMesics lecture 6   control statement = if -else if__else
Mesics lecture 6 control statement = if -else if__else
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Control structure
Control structureControl structure
Control structure
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
 
Control Structures
Control StructuresControl Structures
Control Structures
 

En vedette

Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Abou Bakr Ashraf
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Abou Bakr Ashraf
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Abou Bakr Ashraf
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01PCC
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Abou Bakr Ashraf
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Abou Bakr Ashraf
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net frameworkThen Murugeshwari
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net frameworkArun Prasad
 

En vedette (13)

Quiz 1 answer
Quiz 1 answerQuiz 1 answer
Quiz 1 answer
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
C# basics
 C# basics C# basics
C# basics
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net framework
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 

Similaire à Visula C# Programming Lecture 4

Similaire à Visula C# Programming Lecture 4 (20)

While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
 
M C6java6
M C6java6M C6java6
M C6java6
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.ppt
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
Loops c++
Loops c++Loops c++
Loops c++
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Loops and iteration.docx
Loops and iteration.docxLoops and iteration.docx
Loops and iteration.docx
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
 
Loops in c++
Loops in c++Loops in c++
Loops in c++
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programming
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 

Dernier (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 

Visula C# Programming Lecture 4

  • 2. C# Control Structures: Repetition for structure/foreach structure while structure T F T do/while structure F T F 2
  • 3. while Statement The while statement has the following syntax: while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. while ( condition ) statement; The statement (or a block of statements) is executed repetitively until the condition becomes false. 3
  • 4. while Statement (cont’d) true Product <= 1000 Product = 2 * product false int product; product = 2; while (product <= 1000) { product = 2 * product; } // beginning of the next statement 4
  • 5. while Statement Note that if the condition of a while statement is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times 5
  • 6. Infinite Loops The body of a while loop must eventually make the condition false If not, it is an infinite loop, which will execute until the user interrupts the program This is a common type of logical error You should always double check to ensure that your loops will terminate normally 6
  • 7. Example 1: Counter Controlled While Loop Control variable • The variable used as a counter to determine whether or not the loop should continue Three components • Initial value of the counter • Check whether or not the counter has reached target – When the looping should continue • Incrementing/decrementing of the counter 7
  • 8. Example 2: Sentinel Controlled while Loops This is typical of an input-driven program Continues an arbitrary amount of times Sentinel value • Causes loop to break • Avoid collisions – When flag value = user entered value 8
  • 9. The do Statement The do statement has the following syntax: Uses both the do and while reserved words do { statement; } while ( condition ); The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false 9
  • 10. do/while Flowchart action(s) true condition false Fig. 5.13 Flowcharting the do/while repetition structure. 10
  • 11. Comparing the while and do Loops The while loops vs. the do/while loops Using a while loop • Condition is tested • The action is performed • Loop could be skipped altogether while structure T F do/while structure Using a do/while loop • Action is performed • Then the loop condition is tested • Loop will be run at least once T F Question: write a program to get max from user and then print the numbers from 1 to max 11
  • 12. The for Statement The for statement has the following syntax: Reserved word The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration 12
  • 13. Flowchart of a for loop initialization condition true action(s) increment false for ( initialization ; condition ; increment ) action(s); 13
  • 14. The for Statement: Example Establish initial value of control variable. Determine if final value of control variable has been reached. int counter = 1 counter <= 10 false true Console.WriteLine ( counter * 10 ); Body of loop (this may be multiple statements) counter++ Increment the control variable. for (int counter = 1; counter <= 10; counter++) Console.WriteLine (counter * 10); // beginning of the next statement 14
  • 15. The for Statement A for loop is equivalent to the following while loop: initialization; while ( condition ) { statement; increment; } 15
  • 16. The for Statement It is well suited for executing a specific number of times that can be determined in advance Increment/Decrement • When incrementing – In most cases < or <= is used • When decrementing – In most cases > or >= is used 16
  • 17. The flexibility of the for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Both semi-colons are always required in the for loop header for ( ; ; ) { // do something } 17
  • 18. A Problem to Think About How to print this? xxxxxxxx xxxxxxx xxxxxx xxxxx xxxx xxx xx x What about this? xxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxx xxxxxxx xxxxx xxx x 18
  • 19. Statements break and continue Used to alter the flow of control The break statement • Used to exit a loop early The continue statement • Used to skip the rest of the statements in a loop and restart at the first statement in the loop Programs can be completed without their usage; use with caution. 19