C# .NET: Examples of Loops in C# (for loop, do loop, while loop, foreach loop)

1/29/2014 11:28:06 PM

Examples of different kinds of loops in C#.

  • for Loop
  • for Loop DESCENDING
  • for Loop ASCENDING BY 10
  • for Loop DESCENDING BY 10
  • while Loop
  • do Loop
  • foreach Loop
//FOR LOOP
for (int x = 0; x < 10; x++)
{
	//do something	
}

//FOR LOOP DESCENDING
for (int x = 10; x > 0; x--)
{
	//do something	
}

//FOR LOOP ASCENDING BY 10
for (int x = 0; x < 100; x = x + 10)
{
	//do something	
}

//FOR LOOP DESCENDING BY 10
for (int x = 100; x > 0; x = x - 10)
{
	//do something	
}

//WHILE LOOP
int value = 0;
while (value < 10)
{
	//do something
	value++;        
}

//DO LOOP
value = 0;
do
{
	//do something
	value++;	
} while (value < 10);

//FOREACH
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
    //do something
}