C# Break
The break statement was already utilized in a previous chapter of this lesson. A switch statement was “jumped out” of using it.
Another way to exit a loop is with the break statement.
When i equals 4, this example exits the loop:
Example
C# Continue
If a certain condition is met, the continue statement stops one iteration (of the loop) and moves on to the following iteration.
is omitted:
Example
Break and Continue in While Loop
Break Example
Continue Example
C# Arrays
Create an Array
As an alternative to declaring distinct variables for each value, arrays can hold many values in a single variable.
Use square brackets to define the variable type in order to declare an array:
string[ ] cars;
Now that we have a variable specified, it may hold an array of strings.
We can use an array literal to add values to it by putting the values inside curly braces and in a list separated by commas:
string[ ] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
You could write: in order to generate an array of integers.
int[ ] myNum = {10, 20, 30, 40};
Access the Elements of an Array
This statement accesses the value of the first element in cars :
Example
Change an Array Element
Example
Example
Array Length
Example
Other Ways to Create an Array
You must, however, use the new keyword if you declare an array and initialize it afterwards:
//
Add values without using new (this will cause an error)Loop Through an Array
Using the Length parameter, you can set the number of times the loop should run as you iterate through the array elements using the for loop.
Every entry in the cars array is output in the example that follows:
Example
The foreach Loop
Syntax
Example
When comparing the for loop with foreach loop, you will see that the foreach method is more readable, easier to implement, and does not require a counter because it uses the Length property.
Sort an Array
Example
// sort a string
System.Linq Namespace
Example
Multidimensional Arrays
Two-Dimensional Arrays
Example

Access Elements of a 2D Array
A two-dimensional array requires two indexes to be specified in order to access an element: one index for the array and another index for the element inside the array. Alternatively, much more effectively, with the table representation in mind: one for each row and column (see to the example below).
The value of the element in the numbersz array’s first row (0) and third column (2) is accessed by this statement:
Example
Change Elements of a 2D Array
An element’s value can also be altered.
The value of the element in the first row (0) and first column (0) will be altered by the example that follows:
Example
Loop Through a 2D Array
A foreach loop makes it simple to iterate over the items of a two-dimensional array:
Example
Notably, we must provide the number of times the loop should execute using GetLength() rather than Length: