in C# — Full Code First
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
foreachremoves index management
and lets you focus directly on the element.
If you misunderstand this:
- You overuse
for - You write unnecessary index logic
- Your intent becomes less readable
This lesson is about execution model clarity.
1. What the for Loop Is Actually Doing
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine(words[i]);
}
The only purpose of i here is:
To access
words[i]
We are not using i for logic.
We are using it just to retrieve elements.
The index is a middleman.
2. Understanding the foreach Structure
foreach (string word in words)
{
Console.WriteLine(word);
}
Structure:
foreach (Type variable in Collection)
Meaning:
Take each element inside
words
Assign it toword
Execute the block
No index 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 stop.
Internally, indexing still happens.
But it is abstracted away.
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 shift:
-
for= index-driven loop -
foreach= element-driven loop
5. When Should You Use foreach?
Use foreach when:
- You do not need the index
- You simply process each element
- The operation is read-only
- The order does not need custom control
In other words:
“Perform the same action for every element.”
6. Important Limitation
You cannot directly access the index inside foreach.
This is invalid:
Console.WriteLine(i); // no index variable
Also:
foreach (int number in numbers)
{
number = number * 2; // does NOT modify original array
}
The variable number is a copy.
The original array remains unchanged.
This is a critical distinction.
Final Summary
foreachis the simplest way to iterate over a collection
when you only need the element, not the index.
Learning Check (One Question)
What is the output of this code?
int[] numbers = { 1, 2, 3 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("End");
Answer precisely:
- What is the output order?
- How many iterations occur?
- What determines the number of iterations?
If you can explain this in terms of execution flow,
you understand foreach structurally.
Top comments (0)