Loop
A loop is a programming structure that repeats a sequence of instructions until a specific condition is met. Loops are used very often, that's why you must be comfortable with them.
An example of a loop is a while loop, which states that "while a condition is valid, keep looping". There are other loops in C# as well, as do while, for, and foreach.
Syntax
while (condition)
{
// Do something
}
While Loop Example
int i = 0;
int goal = 7;
while (i < goal)
{
Console.Writeline("We didn't get there yet!");
i++;
}
This block of code would write "We didn't get there yet!" exactly 7 times.
Foor Loop Example
for (var i = 0; i < 7; i++)
{
Console.WriteLine($"Current Index is {i}");
}
/*
* Output
* Current Index is 0
* Current Index is 1
* Current Index is 2
* Current Index is 3
* Current Index is 4
* Current Index is 5
* Current Index is 6
*/
Foreach loop
var names = new List<string> {"Lukasz", "Jan", "John", "Jane", "Monica"};
foreach (var name in names)
{
Console.WriteLine($"How you doin', {name}");
}
/*
* Output
* How you doin' Lukasz
* How you doin' Jan
* How you doin' John
* How you doin' Jane
* How you doin' Monica
*/
And the last one is the do while loop
var knowledgeLevel = 0;
var knowledgeRequired = 1000;
do
{
Console.WriteLine("Keep studying!");
knowledgeLevel++;
} while (knowledgeLevel < knowledgeRequired);
However...
There's one more looping mechanism that you can use. List class has it's own "ForEach" method.
var names = new List<string> {"Lukasz", "Jan", "John", "Jane", "Monica"};
names.ForEach(name => Console.WriteLine($"How you doin', {name}"));
/*
* Output
* How you doin' Lukasz
* How you doin' Jan
* How you doin' John
* How you doin' Jane
* How you doin' Monica
*/
Are you learning C#?
If you're a person that wants to start learning C# and you want to get prepared for your first job - consider joining the .NET School
Top comments (2)
I didn't know about the loop on the list class, and I use loops almost every day! Great post!
Thanks, Erica :)