C# Iteration Constructs
Almost all programming languages I have worked with will have your simple for loop, foreach statments. So, this is just something to practice little on, we will not spend too much time on it:
for loop
foreach / in loop
while loop
do/while loop
We will now examine these looping construct in a new console application.
for Loop
With for loop you can iterate over a block of code with a fixed number of times. That being said, you are able to specify how many times a block of code repeats itself.
One of the short cut to get a for loop statement, without even typing any code is to right click, select "Insert Snippit", then select "for", then customize your for loop. Also instead of writing out "console.wrieline", you may type "cw" then hit tab twice.
for (int i = 0; i < 3; i++)
{ Console.Wireline("Your number is: {0} ", i);
}
foreach Loop
C#'s foreach keyword allowes you to iterate over all items within an array.
static void usingforeachloop()
{
string[] carTypes = { "Honda", "BMW", "Ford", "Mercedez" };
foreach (string a in carTypes)
Console.WriteLine(a);
int[] myIntegers = { 10, 20, 30, 40 };
foreach (int i in myIntegers)
Console.WriteLine(i);
}While and do/While
While looping construct is useful should you wish to execute a block of statements until termination condition has been reached.
static void Whileloop()
{
string userIsFinished = "";
while (userIsFinished.ToLower() != "yes")
{
Console.Write("Are you finished? [Yes] [no]: ");
userIsFinished = Console.ReadLine();
Console.WriteLine("In while loop");
}
Now the difference between while, and do/while loop is that, do/while loop are guarteen to execute atleast one, and incontrast while loop may not execute if the termination condition is false.
do/while loopstatic void doWhileloop()
{
string userIsFinished = "";
do
{
Console.WriteLine("In do/while loop");
Console.WriteLine("Are you done? [yes] [No]: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "yes");
}