- for
- while
- do-while
- foreach
For loops
The for loop is likely what we are all most familiar with. Using a similar syntax to what we have seen in Java, the construction of a for loop uses a variable, a condition on that variable, and a post-loop action. An example of such is shown below:
This loop is very straight forward, and no different than what we have seen before in Java.
While loops
The while loop is once again familiar. This loop requires that a variable must be declared before entering the loop condition. In other words, we must have initialized a variable to put conditions on before anything happens. An example of a while loop is shown below:
We can see the similarity of this to a for loop, but with the syntax of it being performed in different locations in the code.
Do-While loops
The do-while loop is not much different from a while loop. In this version of a loop, the actions are performed before the conditions are stated. Really, if we take the "while (condition)" from the top, and place it on the bottom of the loop, we have created the do-while. An example is shown below:
Foreach loops
The foreach loop is something that requires no condition, and is best exemplified by performing on an array. What happens here is the code within the loop is performed for each item in the array. The code for this version of a loop is shown below:
So we can see that there are many ways to get the same outputs using loops in C#. There are some methods which are similar to what we have seen before, along with some new ways of achieving results. Personal preferences can be taken into account writing code for loops.
No comments:
Post a Comment