Foreach Loop
Part of the Fundamentals section of Coddy's C# journey — lesson 65 of 69.
The foreach loop, also known as the enhanced for loop, provides a simpler way to iterate through arrays and collections. It automatically handles the indexing and retrieval of elements, making the code more readable and less prone to errors.
Here's the basic syntax of an foreach loop:
foreach (data_type element in array_or_collection) {
// Code to be executed for each element
}data_type: The type of elements in the array or collection.element: A variable that will hold the current element in each iteration.array_or_collection: The array or collection you want to iterate over.
Here's an example:
int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers) {
Console.WriteLine(number);
}In this example, the loop iterates over the numbers array. In each iteration, the current element is assigned to the number variable, and the code inside the loop is executed. The output will be:
1
2
3
4
5The foreach loop is especially useful when you need to access each element in a collection without modifying the collection itself. It simplifies the code and makes it more readable.
Challenge
EasyCreate a program that does the following:
- Initializes an array of strings named
fruitswith the values"apple","banana","orange","grape", and"kiwi". - Uses a
foreachloop to iterate over thefruitsarray. - In each iteration, prints the current fruit in uppercase using the
ToUpper()method:someString.ToUpper()
Cheat sheet
The foreach loop provides a simpler way to iterate through arrays and collections without manual indexing:
foreach (data_type element in array_or_collection) {
// Code to be executed for each element
}Example with an integer array:
int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers) {
Console.WriteLine(number);
}The foreach loop automatically handles indexing and element retrieval, making code more readable and less error-prone.
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
// Initialize the fruits array
// Use a foreach loop to iterate over the array
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3