Full Runnable Code
using System;
class Program
{
static void Main()
{
string[] words = { "apple", "banana", "cherry" };
Console.WriteLine("Using for loop:");
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine(words[i]);
}
Console.WriteLine();
Console.WriteLine("Using foreach loop:");
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.ReadKey();
}
}
0. The Real Goal of This Lesson
foreachlets you iterate over elements directly without managing indices.
If this is not clear:
- you overuse
for - you write unnecessary index logic
- your code becomes less readable
This lesson is about understanding element-based iteration.
1. What the for Loop Is Actually Doing
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine(words[i]);
}
The role of i is only this:
To access
words[i]
We are not using i for logic.
We are using it as a tool to retrieve elements.
So structurally:
for= index-driven access
2. Understanding the foreach Structure
foreach (string word in words)
{
Console.WriteLine(word);
}
Structure:
foreach (Type variable in Collection)
Meaning:
Take each element from
words
Assign it toword
Execute the block
No index is required.
3. Step-by-Step Execution Flow
Array:
["apple", "banana", "cherry"]
First iteration
word = "apple"
print
Second iteration
word = "banana"
print
Third iteration
word = "cherry"
print
Then the loop ends.
Important:
Indexing still happens internally, but it is hidden from you.
4. for vs foreach — Structural Difference
| Criteria | for | foreach |
|---|---|---|
| Focus | Index | Element |
| Index access | Yes | No |
| Readability | Medium | Higher |
| Use case | When index control is needed | When simple traversal is needed |
Mental model:
-
for→ control the iteration -
foreach→ consume elements
5. When Should You Use foreach?
Use foreach when:
- you do not need the index
- you process all elements
- the operation is read-only
- no custom stepping logic is required
In short:
“Do the same operation for every element.”
6. Important Limitation
You cannot directly use an index inside foreach.
This is invalid:
Console.WriteLine(i);
There is no i.
Modification Does Not Affect Original Data
foreach (int number in numbers)
{
number = number * 2; // does NOT change the array
}
Reason:
numberis a copy of the element, not the original reference.
So the original array remains unchanged.
Final Summary
foreachis the simplest way to iterate through a collection when you only need the element, not the index.
Learning Check
Consider this code:
int[] numbers = { 1, 2, 3 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("End");
Explain:
- What is the output order?
- How many times does the loop run?
- What determines the number of iterations?
Answer using execution flow, not just results.
Top comments (0)