SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a C# Loops Guide - Learn for, while, do while loops in C

Similar a C# Loops Guide - Learn for, while, do while loops in C (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
 

Último

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Último (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

C# Loops Guide - Learn for, while, do while loops in C

  • 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