In C#, it is possible to manage the execution of code with different control structures. In this article, we will look at loops. Loops can be used to repeat parts of a code a specified number of times or until a certain condition is met.
C# While Loops
The syntax for a while loop is:
The syntax can almost be directly translated into English: do something while a condition is met.
Let’s look at a simple example:
In the example, a variable named
i is used. As you can see, variables in C# always start with a datatype int in our case.
Apart from that, the example is almost self-explanatory. First the variable
i is set to be equal to 1. Then the loop asks the .NET to repeat the text while
i is less or equal to 50. In each loop, the variable
i will be increased by 1.
C# Do-While Loops
A ‘do-while’ loop is just like a ‘while’ loop except that the condition is evaluated after the block of code specified in the ‘do’ clause has been run. So even where the condition is initially false, the block runs once. For instance, the following code outputs ‘4’:
C# For Loops
Another way to make a loop is with for statement in the following form:
The statement is repeated as long as ‘Initialization’ + ‘Step’ meets the ‘Condition’. If that doesn’t make sense, look at this example:
In the example above,
i is growing with the value 5 in each loop. The loop will continue as long as
i is below or equals 50. Also note how the value
i is used as part of the sentence.
C# Nested Loops
In principle, there are no limitations on how loops can be used. For instance, you can easily put loops inside loops and thereby create many repeats.
In this example, we have created a multiplication table from 1 to 10 you can easily change the value for variable i and j and extend the table.
C# Foreach Loops
The ‘foreach’ loop is used to iterate through the values contained by any object which implements the IEnumerable interface. When a ‘foreach’ loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2. As we have seen previously, such loops can be used to access array values. So, we could loop through the values of an array in the following way:
The main drawback of ‘foreach’ loops is that each value extracted (held in the given example by the variable ‘b’) is read-only.
Subscribe to Code with Shadman
Get the latest posts delivered right to your inbox