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.
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
{
staticvoid Main()
{
int[] numbers = {1, 2, 3, 4, 5};
// Using for loopfor (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 arrayfor (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 loopfor (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 lastfor (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
{
staticvoid 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.
Practice
(1/5)
1. Which loop is best when you want to access each element in an array without needing the index in C#?
easy
A. foreach loop
B. for loop
C. while loop
D. do-while loop
Solution
Step 1: Understand loop purpose
foreach is designed to iterate over each element directly without needing the index.
Step 2: Compare with other loops
for requires index management, while and do-while are less direct for arrays.
Final Answer:
foreach loop -> Option A
Quick Check:
Direct element access = foreach [OK]
Hint: Use foreach when index is not needed for array items [OK]
Common Mistakes:
Choosing for loop when index is not required
Confusing while loops with foreach
Thinking foreach can modify array size
2. Which of the following is the correct syntax for iterating over an array named numbers using a for loop in C#?
easy
A. for (int i = 0; i < numbers.Count; i++) { Console.WriteLine(numbers[i]); }
B. for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); }
C. for (int i = 0; i <= numbers.Length; i++) { Console.WriteLine(numbers[i]); }
D. for (int i = 1; i <= numbers.Length; i++) { Console.WriteLine(numbers[i]); }
Solution
Step 1: Check loop start and end conditions
Index starts at 0 and runs while less than numbers.Length (array length).
Step 2: Validate index usage
Accessing numbers[i] is correct; using Count is invalid for arrays.
Final Answer:
for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } -> Option B
Quick Check:
Index 0 to Length-1 = correct for loop [OK]
Hint: Use i < array.Length, not <= or Count for arrays [OK]
Common Mistakes:
Using i <= numbers.Length causing out-of-range error
Starting index at 1 instead of 0
Using Count property on arrays
3. What will be the output of the following C# code?
int[] nums = {1, 2, 3};
int sum = 0;
foreach (int n in nums) {
sum += n;
}
Console.WriteLine(sum);
medium
A. Error
B. 123
C. 0
D. 6
Solution
Step 1: Understand foreach iteration
The loop adds each element (1, 2, 3) to sum one by one.
Step 2: Calculate sum
sum = 0 + 1 + 2 + 3 = 6
Final Answer:
6 -> Option D
Quick Check:
Sum of array elements = 6 [OK]
Hint: Sum elements by adding each in foreach loop [OK]
Common Mistakes:
Concatenating numbers instead of adding
Forgetting to initialize sum to 0
Using for loop incorrectly causing index errors
4. Identify the error in this C# code snippet:
int[] arr = {10, 20, 30};
for (int i = 0; i <= arr.Length; i++) {
Console.WriteLine(arr[i]);
}
medium
A. The loop condition should be i < arr.Length, not i <= arr.Length
B. The array declaration is incorrect
C. Console.WriteLine cannot print array elements
D. The loop variable i should start at 1
Solution
Step 1: Check loop boundary
Using i <= arr.Length causes index out of range because last valid index is Length - 1.
Step 2: Correct loop condition
Change condition to i < arr.Length to avoid runtime error.
Final Answer:
The loop condition should be i < arr.Length, not i <= arr.Length -> Option A
Quick Check:
Index must be less than Length [OK]
Hint: Use i < array.Length to avoid out-of-range errors [OK]
Common Mistakes:
Using <= instead of < in loop condition
Starting index at 1 instead of 0
Misunderstanding array length vs last index
5. You have an array string[] fruits = {"apple", "banana", "cherry"};. You want to create a new array with all fruit names in uppercase using a for loop. Which code correctly does this?
hard
A. string[] upperFruits = new string[fruits.Length];
for (int i = 1; i <= fruits.Length; i++) {
upperFruits[i] = fruits[i].ToUpper();
}
B. string[] upperFruits = new string[fruits.Length];
foreach (string f in fruits) {
upperFruits[i] = f.ToUpper();
}
C. string[] upperFruits = new string[fruits.Length];
for (int i = 0; i < fruits.Length; i++) {
upperFruits[i] = fruits[i].ToUpper();
}
D. string[] upperFruits = new string[fruits.Length];
for (int i = 0; i < fruits.Length; i++) {
upperFruits[i] = fruits.ToUpper();
}
Solution
Step 1: Initialize new array with same length
We create upperFruits with the same size as fruits.
Step 2: Use for loop with correct index and method
Loop from 0 to Length-1, assign fruits[i].ToUpper() to upperFruits[i].
Final Answer:
string[] upperFruits = new string[fruits.Length]; for (int i = 0; i < fruits.Length; i++) { upperFruits[i] = fruits[i].ToUpper(); } -> Option C
Quick Check:
Use for loop with index and ToUpper() per element [OK]
Hint: Use for loop with index to assign transformed elements [OK]
Common Mistakes:
Using foreach without index to assign array elements
Starting loop at 1 or using <= causing errors
Calling ToUpper() on array instead of string element
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.