Changes

Jump to: navigation, search

C Sharp Looping - The for Statement

2,188 bytes added, 16:48, 17 January 2008
Breaking Out of a for Loop
<pre>
int j = 10;
 
for (int i = 0; i < 100; i++)
{
j += j;
 
if (j > 100)
break;
}
</pre>
 
In the above example the loop will continue to execute until the value of j exceeds 100 at which point the loop will exit.
 
== Nested for Loops ==
 
So far we have looked at only a single level of ''for'' loop. It is also possible to nest for loops where one for loop resides inside another for loop. For example:
 
<pre>
for (int i = 0; i < 100; i++)
{
System.Console.WriteLine ( "i = " + i);
 
for (int j = 0; j < 10; j++)
{
System.Console.WriteLine ( "j = " + j);
}
}
</pre>
 
The above example will loop 100 times displaying the value of i on each iteration. In addition for each of those iterations it will loop 10 times displaying the value of j.
 
== Breaking From Nested Loops ==
 
An important point to be aware of when breaking out of a nested for loop is that the break only exits from the current level of loop. For example, the following C# code example will exit from the current iteration of the nested loop when j is equal to 5. the outer loop will, however, continue to iterate and execute the nested loop:
 
<pre>
for (int i = 0; i < 100; i++)
{
System.Console.WriteLine ( "i = " + i);
 
for (int j = 0; j < 10; j++)
{
if (j == 5)
break;
 
System.Console.WriteLine ( "j = " + j);
}
}
</pre>
 
== Continuing for Loops ==
 
Another useful statement for use in loops in the ''continue'' statement. When the execution process finds a continue statement in any kind of loop it skips all remaining code in the body of the loop and begins execution once again from the top of the loop. Using this technique we can construct a for loop which outputs only even numbers:
 
<pre>
for (int i = 0; i < 20; i++)
{
if ((i % 2) != 0)
continue;
 
System.Console.WriteLine ( "i = " + i);
}
}
</pre>
 
In the example, if i is not divisible by 2 with 0 remaining the code performs a ''continue'' sending execution to the top of the for loop, thereby bypassing the code to output the value of i. This will result in the following output:
 
<pre>
0
2
4
6
8
</pre>
== Nested for Loops ==
So far we have looked at only a single level of ''for'' loop. It is also possible to nest for loops where one for loop resides inside another for loop.

Navigation menu