SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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 to Visula C# Programming Lecture 4

Similar to 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
 

Recently uploaded

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
 
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
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

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 ...
 
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
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
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...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

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