create a loop in csharp

In C#, there are several ways to create loops. Here are three of the most commonly used:

1. The while Loop

The while loop continues iterating through a block of code as long as a specified condition remains true.

main.cs
while (condition)
{
  // code to execute while condition is true
}
67 chars
5 lines

2. The for Loop

The for loop allows you to iterate through a block of code a specific number of times.

main.cs
for (int i = 0; i < count; i++)
{
  // code to execute during each iteration
}
79 chars
5 lines

3. The foreach Loop

The foreach loop is used to iterate through collections, such as arrays or lists.

main.cs
foreach (var item in collection)
{
  // code to execute during each iteration
}
80 chars
5 lines

Here is an example of each type of loop in action:

main.cs
// while loop example
int i = 0;
while (i < 5)
{
  Console.WriteLine(i);
  i++;
}

// for loop example
for (int j = 0; j < 5; j++)
{
  Console.WriteLine(j);
}

// foreach loop example
int[] nums = { 1, 2, 3, 4, 5 };
foreach (int num in nums)
{
  Console.WriteLine(num);
}
272 chars
21 lines

Output:

main.cs
0
1
2
3
4
0
1
2
3
4
1
2
3
4
5
30 chars
16 lines

related categories

gistlibby LogSnag