Changes

Jump to: navigation, search

C Sharp Looping - The for Statement

10 bytes added, 15:26, 1 April 2009
no edit summary
== Why Use Loops? ==
It is generally common knowledge that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowledge that computers really don't do anything unless someone programs them to tell them what to do. Loop statements are the primary mechanism for telling a computer that a sequence of tasks needs to perform the be repeated a specific number of times. Suppose, for example, that you have a requirement to add a number to itself ten times. One way to do this might be to write the following C# code:
<pre>
</pre>
Whilst this is somewhat cumbersome it does work. What would happen, however, if you needed to perform this task 100 times or even 10,000 times. ? Writing C# code to perform this as above would be prohibitive. Such a scenario is exactly what the ''for'' loop is intended to handle.
The syntax of a C# ''for loop'' is as follows:
== C# Loop Variable Scope ==
A key point to note in creating loops is that any variables defined within the body of a loop is are only visible to code within the loop. This is concept known as ''scope''. If, for example, a variable ''myCounter'' is defined in a for loop, that variable ceases to exist once the loop terminates:
<pre>
== Breaking Out of a for Loop ==
Having created a loop it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met (and particularly if you have created an infinite loop). One such example might involve continually checking for activity on a network socket. Once activity has been detected it will be necessary to break out of the monitoring loop and perform some other task.
For the purpose of breaking out of a loop C# provides the ''break'' statement which breaks out of the current loop and resumes execution at the code directly after the loop. For example:

Navigation menu