In this article, we'll learn about how to use loops in C#.
In C# there are 4 types of loops available -
- for
- foreach
- while
- do-while
The for
loop
The for loop is a basic loop that is available in almost all programming languages. It executes a block of statements until a specified expression evaluates to false.
Syntax
for(initialValue; condition; iterator)
{
statements...
}
The above code executes the statements inside parentheses until the condition evaluates to false.
Example
for(int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
The foreach
loop
The foreach loop in C# is used to iterate over the instance of the type that implements the IEnumerable
or IEnumerable<T>
interface. In other words, it is used to iterate over an array or collection.
Syntax
foreach(type variable in collection)
{
statements...;
}
Iterate on Array
In this example we'll use a simple array of integers.
int[] numbers = {1,2,3,4,5};
foreach(int number in numbers)
{
Console.WriteLine(number);
}
The above lines will print all the numbers in the list numbers
.
1
2
3
4
5
Iterate on Collection
In this example, we are going to use collections.
using System.Collections.Generic;
...
...
List<string> people = new List<string> {"John","Smith","Josh","Walton"};
foreach(string name in people)
{
Console.WriteLine(name);
}
The above lines will print all the names from the collection people
.
John
Smith
Josh
Walton
The while
loop
The while loop executes a block of statements while an expression evaluates to true.
Syntax
while(condition)
{
statements...
}
Example
int j = 0;
while (j<5)
{
Console.Write(j);
j++;
}
The do-while
loop
The do-while loop executes a block of statements while an expression evaluates to true. The only difference in this and while loop is that, it executes the block at least one time since the condition is checked after the execution of the loop.
Syntax
do
{
statements...
} while (condition)
Example
int k = 1;
do
{
Console.Write(k);
k++;
} while(k<5)
Top comments (0)