This is the second part of a three-part series on C# Iterative Statements. In the first part, we delved into while
/do while
loop. Check it out in case you missed it.
In this guide, we will focus on another important loop: for
/foreach
loop.
As this will be a guide for beginners, I try my best to use vivid visualizations and examples to help you understand.
Imagine this scenario:
This time, we develop a cleaning robot. We will give it a task list, like {"bedroom", "kitchen", "toilet"}, and it should clean them all.
for
and foreach
loop are good choices to solve this problem.
for
By convention, we learn the syntax of for
statement first:
1for (initializer; condition; update_expression)
2{
3 code_block;
4}
The for
statement is composed of initializer
, condition
, update_expression
, code_block
:
code_block
represents the logic executed in the loop. It could include multiple statements, even another loop block.initializer
is the logic you want to execute before entering the loop. Usually, it is for the initialization of loop variables.condition
is a boolean expression. It decides whether it should continue looping or exit loop.update_expression
defines update expressions in every loop. It is executed after code_block
. Like initializer
, it is for the update of loop variables as usual.Please take a look at the for
loop flowchart. It shows flow control intuitively.
Through the above flowchart, we can figure out the execution process of for
loop:
initializer
is executed exactly once. It is a good opportunity to declare and initialize loop variables.condition
. If satisfied, run loop logic code_block
. Otherwise, terminate the loop.code_block
, execute update_expression
. Update loop variable here for next condition
check.condition
again. Repeat this process until condition==False
.Since we have learned the mechanism of for loop, it is time to solve an example problem:
1string[] tasks = {"bedroom", "kitchen", "toilet"};
2// loop variable i presents the index of tasks array
3for (int i = 0; i < tasks.Length; ++i)
4{
5 Console.WriteLine("mission complete: clean {0}", tasks[i]);
6}
7/*output:
8mission complete: clean bedroom
9mission complete: clean kitchen
10mission complete: clean toilet */
Each of these four sections - initializer
, condition
, update_expression
, and code_block
- could be optional. Also, they could include multiple statements:
code_block
uses ;
to separate statements.initializer
and update_expression
use ,
to separate statements.||
or &&
to connect boolean expressions. Let's practice multiple statements in all of the sections from this complex example:
You’re given two numbers:
x
andy
.x
starts from 0, add 1 each time;y
starts from 12, subtract 2 each time. Calculate the difference betweeny
andx
repetitively whenx
is not greater thany
and production is less than 18.
1// x starts from 0 and add 1 each time; y starts from 12 and subtract 2 each time
2// iteration when x is not greater than y and production less than 18
3for (int x = 0, y = 12; x <= y && x * y < 18; ++x, y -= 2)
4{
5 // calculate difference between y and x, then print out
6 int difference = y - x;
7 Console.WriteLine("x={0}, y={1}, difference={2}", x, y, difference);
8}
9/* output:
10x=0, y=12, difference=12
11x=1, y=10, difference=9
12x=2, y=8, difference=6 */
foreach
For the scenario about accessing elements in a collection, foreach
is the best solution.
The syntax of foreach
:
1foreach (element in IEnumerable)
2{
3 code_block;
4}
element
represents the current element in a collection.IEmuerable
represents a collection-like data structure which implements the interface IEnumerable
. We will talk about this later.code_block
is similar to others. It represents the logic executed in the loop.The foreach
loop flowchart visualizes the flow control process:
IEnumberable
has any elements left.element
and process in code_block
. Otherwise, exit loop.IEnumberable
is exhausted.For the above scenario, foreach the element in string array tasks
:
1string[] tasks = {"bedroom", "kitchen", "toilet"};
2// foreach the element in string array tasks
3foreach (string task in tasks)
4{
5 Console.WriteLine("mission complete: clean {0}", task);
6}
foreach
supports iterating an element in all kinds of IEnumerable
. So what is IEnumberable
?
An easily understandable explanation is that IEnumberable
is a collection-like data structure, such as int[]
, List
, Dictionary
, or DataRow
.
A more formal illustration is that foreach
covers the type which implements the interface IEnumberable or
IEnumberable. This type returns an element by GetEnumerator()
; an element should implement two essential features to support foreach
:
Current
property to help foreach
access the current element.bool MoveNext()
to check whether we can get the next element (return false when reaching the end). We are not going to expand here. I have attached official documents in case you want to dive into it:
for
vs foreach
while
vs do while
, you can consider foreach
as the extension of for
. It is typically used when you focus on processing an element of a collection in a loop. for
deals with the index of collection and accesses an element by the index indirectly. So, if we want to access an element of a collection in order, and care nothing about the index, foreach
is the best practice.for
loop is widely used without any restriction, but foreach
has some limitations:element
is permitted).In this part, we have learned the other iterative statements: for
and foreach
. We analyzed the syntax and flowchart of for
/foreach
and practiced them with examples. Furthermore, we made a comparison of them.
In the last part, we will compare them and summarize the best practices. In addition, we will explore advanced usages.
As this is the end, I have drawn a mind map to help you organize and review the knowledge in this series.
This guide is one of a series of C# Flow Control guides:
Hope you enjoyed it. If you have any questions, you’re welcome to contact me at [email protected]