2. Foreach Loop
Using Break with Exit
Continue Statement
Return Statement
Goto Statements
Table of Contents:
3. The foreach loop is used to cycle through the
elements of a collection. A collection is a
group of objects. C# defines several types of
collections, of which one is an array. The general
form of foreach is shown here:
foreach(type loopvar in collection) statement;
Foreach Loop:
4. Simple C# Code of “Foreach Loop”
int[] nums = new int[5];
for(int i = 0; i <=4; i++)
nums[i] = i;
foreach(int x in nums) {
Console.WriteLine("Value is: " + x);
OutPut:
Value is: 0
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Foreach loop:
5. It is possible to force an immediate exit from a loop,
bypassing any code remaining in the body of the loop
and the loop’s conditional test, by using the break
statement. When a break statement is encountered
inside a loop, the loop is terminated, and program
control resumes at the next statement following the
loop. Here is a simple example:
for(int i=-10; i <= 10; i++) {
if(i > 0) break;
Console.Write(i + " ");}
Using break with Exit:
6. It is possible to force an early iteration of a loop, bypassing
the loop’s normal control structure. This is accomplished
using continue. The continue statement forces the next
iteration of the loop to take place, skipping any code in
between. Thus, continue is essentially the complement
of break. For example, the following program uses continue
to help print the even numbers
between 0 and 100.
for(int i = 0; i <= 100; i++) {
if((i%2) != 0) continue; // iterate
Console.WriteLine(i);
Using continue statements:
7. The return statement terminates execution of the method in
which it appears and returns control to the calling method. It
can also return an optional value. If the method is a void type,
the return statement can be omitted.
A return statement is used for returning value to the caller
from the called function. A easy example is mentioned
below in a program that demonstrate the return statement
very clearly.
public int add(int num1, int num2)
{
// returns the add of num1 and num2
return num1 + num2;
}
Return Statement:
8. The goto is C#’s unconditional jump statement. When
encountered, program flow jumps to the location specified
by the goto.
The goto requires a label for operation. A label is a valid C#
identifier followed by a
colon. The label must be in the same method as the goto
that uses it and within scope. For
example, a loop from 1 to 100 could be written using a goto
and a label, as shown here:
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
Goto Statement: