TIPS
For infinite loops. It is recommended to use while loops for infinite loops as for loops will throw an exeption. {: .prompt-tip}
for loops
for loops have an increments and will run until the increments runs out
for (var i = 0; i < 3; i++)
{
// Code here will run 3 times
Console.WriteLine(i);
}
// >>> 0, 1, 2
foreach loop
this loops runs thru enumerable objects and iteratables.
foreach (var item in items)
{
}
while loop
this loop will run as long as the codition remainds true. If the condition is false. the loop will not execute
var condition = true;
while (condition)
{
// execute this block of code repetively.
}
do while loop
Like while loop. This do while loops will run at least once regardless of whether or not the condition is true or false.
var condition;
do
{
// This block of code will execute at least once.
// Will run repetively if condition is true
} while (condition)
break and continue
break and continues are used in loops to interrupt the loop. Often times from within if else statements.
break
break statement immediately interrupts the flow and terminates the loop.
The bottom example shows how we would use break to break out of the infinite while loop when the user prompts.
var numbers = new List<int>();
while (true)
{
Console.WriteLine("Enter a number");
var user_input = Console.ReadLine();
//For simplicity sake. Null and invalid exeption handling are not implemented.
if (user_input == "ok")
{
break;
}
else
{
numbers.Add(Convert.ToInt32(user_input));
}
}
continue
continue interrupts the flow and skips to the subsequent literation.
for (var i = 0; i <10; i++)
{
if (i % 2 == 0)
{
Console.WriteLine("{0} is an even number", i);
continue;
}
// This line doesnt execute if the contine statement executes
Console.WriteLine("An odd number!")
}