creat a loop in csharp

There are several ways to create loops in C#:

  1. for loop:
main.cs
for(int i = 0; i < 10; i++)
{
   // code to be executed
}
58 chars
5 lines

The above code will generate a loop that runs 10 times.

  1. while loop:
main.cs
int i = 0;
while(i < 10)
{
   // code to be executed
   i++;
}

64 chars
8 lines

The above code will generate a loop that runs until i is less than 10.

  1. do-while loop:
main.cs
int i = 0;
do 
{
   // code to be executed
   i++;
} 
while (i < 10);

71 chars
9 lines

The above code will generate a loop that runs until i is less than 10, but executes at least once even if the condition is false.

  1. foreach loop:
main.cs
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int x in numbers)
{
   // code to be executed
}

93 chars
7 lines

The above code will generate a loop that iterates through each element of the array numbers.

  1. goto loop:
main.cs
int i = 0;
loop:
   // code to be executed
i++;
if (i < 10)
   goto loop;
74 chars
7 lines

The above code will generate a loop that runs until i is less than 10, but uses a goto statement to jump back to the top of the loop.

It is recommended to use the for, while, do-while, and foreach loops, while goto loops should be avoided as it makes code less readable and maintainable.

related categories

gistlibby LogSnag