We use array iteration to look at each item in a list one by one. This helps us do something with every item, like print or check it.
0
0
Array iteration with for and foreach in C Sharp (C#)
Introduction
When you want to print all items in a list of names.
When you need to add up all numbers in an array.
When you want to find a specific item in a list.
When you want to change or update each item in a list.
When you want to count how many items meet a condition.
Syntax
C Sharp (C#)
class Program { static void Main() { int[] numbers = {1, 2, 3, 4, 5}; // Using for loop for (int index = 0; index < numbers.Length; index++) { int currentNumber = numbers[index]; // Do something with currentNumber } // Using foreach loop foreach (int currentNumber in numbers) { // Do something with currentNumber } } }
The for loop uses an index to access each item by position.
The foreach loop goes through each item directly without using an index.
Examples
Both loops do nothing because the array is empty.
C Sharp (C#)
int[] emptyArray = {}; // for loop on empty array for (int i = 0; i < emptyArray.Length; i++) { Console.WriteLine(emptyArray[i]); } // foreach loop on empty array foreach (int item in emptyArray) { Console.WriteLine(item); }
Both loops print the single item once.
C Sharp (C#)
int[] singleItemArray = {42}; // for loop for (int i = 0; i < singleItemArray.Length; i++) { Console.WriteLine(singleItemArray[i]); } // foreach loop foreach (int item in singleItemArray) { Console.WriteLine(item); }
Both loops print only the first and last items.
C Sharp (C#)
int[] numbers = {10, 20, 30}; // for loop accessing first and last for (int i = 0; i < numbers.Length; i++) { if (i == 0 || i == numbers.Length - 1) { Console.WriteLine(numbers[i]); } } // foreach loop with condition foreach (int number in numbers) { if (number == 10 || number == 30) { Console.WriteLine(number); } }
Sample Program
This program shows how to go through an array of scores using both for and foreach loops. It prints each score with its position for the for loop and just the score for the foreach loop.
C Sharp (C#)
using System; class Program { static void Main() { int[] scores = {85, 92, 78, 90, 88}; Console.WriteLine("Scores using for loop:"); for (int index = 0; index < scores.Length; index++) { Console.WriteLine($"Score at index {index}: {scores[index]}"); } Console.WriteLine("\nScores using foreach loop:"); foreach (int score in scores) { Console.WriteLine($"Score: {score}"); } } }
OutputSuccess
Important Notes
The for loop is useful when you need the position (index) of each item.
The foreach loop is simpler when you only need the item itself.
Both loops run in time proportional to the number of items (O(n)).
Summary
Use for to access items by index.
Use foreach to access items directly.
Both loops help you do something with every item in an array.