C# Array, Loop
Last modified: July 11, 2021When you know how many times need to loop, you can use for loop
instead of while
loop.
static void Main(string[] args)
{
var numbersOne = new List<int>() {10, 4, 8 };
for(int i = 0; i < numbersOne.Count; i ++ )
{
Console.WriteLine(numbersOne[i]);
}
}
static void Main(string[] args)
{
var numbersOne = new List<int>() {10, 4, 8 };
foreach(var i in numbersOne)
{
Console.WriteLine(i);
}
}
When you do not know many times a loop needs but you know when a condition to exit loop, then while
loop is used.
static void Main(string[] args)
{
var numbersOne = new List<int>() {10, 4, 8 };
var index = 0;
while (index < numbersOne.Count)
{
Console.WriteLine(numbersOne[index]);
index++;
}
}