When you know exactly how many times you want to loop through a block of code, the for loop is a much cleaner option than a while loop. It condenses the initialization, condition check, and increment step into a single line.
for Loop Syntaxfor (statement 1; statement 2; statement 3) { // code block to be executed }
using System;class Program { static void Main() { // This prints numbers 0 to 4 for (int i = 0; i < 5; i++) { Console.WriteLine(i); } } }
foreach LoopC# offers an incredible loop designed specifically to loop through arrays and collections: the foreach loop. It is cleaner and prevents "index out of bounds" errors.
using System;class Program { static void Main() { // An array of cars string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); } } }
We will cover arrays in much more detail shortly, but as you can see, foreach makes reading through a list of items very simple!
Which loop is specifically designed to easily read through an array?