A Comprehensive Walkthrough of C# Iterative Statements Part 2 - for, foreach
Analyze the syntax and flowchart of for/foreach and practice them with examples.
Jun 14, 2019 • 9 Minute Read
Introduction
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.
- First, I will start with an interesting scenario.
- Then I will show you the code templates and flowcharts of iterative statements.
for Loop
Scenario
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
Syntax
By convention, we learn the syntax of for statement first:
for (initializer; condition; update_expression)
{
code_block;
}
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.
Flowchart
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:
-
Before the loop, initializer is executed exactly once. It is a good opportunity to declare and initialize loop variables.
-
Check whether to satisfy condition. If satisfied, run loop logic code_block. Otherwise, terminate the loop.
-
After code_block, execute update_expression. Update loop variable here for next condition check.
-
Go back to step two to judge condition again. Repeat this process until condition==False.
Practice
Since we have learned the mechanism of for loop, it is time to solve an example problem:
string[] tasks = {"bedroom", "kitchen", "toilet"};
// loop variable i presents the index of tasks array
for (int i = 0; i < tasks.Length; ++i)
{
Console.WriteLine("mission complete: clean {0}", tasks[i]);
}
/*output:
mission complete: clean bedroom
mission complete: clean kitchen
mission complete: clean toilet */
Advanced Usage
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.
- condition use || 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 and y. x starts from 0, add 1 each time; y starts from 12, subtract 2 each time. Calculate the difference between y and x repetitively when x is not greater than y and production is less than 18.
// x starts from 0 and add 1 each time; y starts from 12 and subtract 2 each time
// iteration when x is not greater than y and production less than 18
for (int x = 0, y = 12; x <= y && x * y < 18; ++x, y -= 2)
{
// calculate difference between y and x, then print out
int difference = y - x;
Console.WriteLine("x={0}, y={1}, difference={2}", x, y, difference);
}
/* output:
x=0, y=12, difference=12
x=1, y=10, difference=9
x=2, y=8, difference=6 */
foreach
Syntax
For the scenario about accessing elements in a collection, foreach is the best solution.
The syntax of foreach:
foreach (element in IEnumerable)
{
code_block;
}
- 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.
Flowchart
The foreach loop flowchart visualizes the flow control process:
- Check whether IEnumberable has any elements left.
- If it has, assign to element and process in code_block. Otherwise, exit loop.
- Repeat this process until IEnumberable is exhausted.
Practice
For the above scenario, foreach the element in string array tasks:
string[] tasks = {"bedroom", "kitchen", "toilet"};
// foreach the element in string array tasks
foreach (string task in tasks)
{
Console.WriteLine("mission complete: clean {0}", task);
}
Scope of Usages
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<T>. This type returns an element by GetEnumerator(); an element should implement two essential features to support foreach:
- Implement Current property to help foreach access the current element.
- Implement 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
- Similar to 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 element iteration case, 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:
- It is unable to modify the collection when iterating (modifying the member of element is permitted).
- It does not track the index, so it does not support index operations in a loop.
- The iteration order can only be forward. It does not support to traversing in reverse or random order.
- You can not add an extra condition to filter elements.
Conclusion
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:
- A Comprehensive Walkthrough of C# Iterative Statements Part 1 - while, do
- A Comprehensive Walkthrough of C# Iterative Statements Part 2 - for, foreach
- A Comprehensive Walkthrough of C# Iterative Statements Part 3 - advanced usages
- A Comprehensive Walkthrough of C# Conditional Statements Part 1 - if, else
- A Comprehensive Walkthrough of C# Conditional Statements Part 2 - switch
- A Comprehensive Walkthrough of C# Jump Statements Part 1 - break, continue
- A Comprehensive Walkthrough of C# Jump Statements Part 2 - goto
Hope you enjoyed it. If you have any questions, you’re welcome to contact me at recnac@foxmail.com.