For in C#
C# provides several looping constructs. Here are some basic types of loops.
The most basic type is a while
loop with a single condition. It’s similar to the first example in the original code.
A classic for
loop in C# is identical to many other C-style languages, with initial, condition, and increment parts.
C# doesn’t have a direct equivalent to Go’s range
over an integer, but we can use foreach
with Enumerable.Range()
to achieve a similar effect.
An infinite loop in C# can be created with while (true)
. You can use break
to exit the loop or return
to exit the entire method.
The continue
keyword works the same way in C# as it does in many other languages, skipping to the next iteration of the loop.
To run this program, save it as Program.cs
and use the dotnet
command:
C# offers other looping mechanisms as well, such as do-while
loops and more advanced foreach
loops for iterating over collections and other enumerable objects.