C#-Break, Continue & Arrays

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

      for (int i = 0; i < 10; i++)
      {
        if (i == 4)
        {
          break;
        }
        Console.WriteLine(i);
      }
 

C# Continue

If a certain condition is met, the continue statement stops one iteration (of the loop) and moves on to the following iteration.

In this instance, the number 4
is omitted:
 

Example

      for (int i = 0; i < 10; i++)
      {
        if (i == 4)
        {
          continue;
        }
        Console.WriteLine(i);
      }
 

Break and Continue in While Loop

In while loops, you may also use break and continue:

Break Example

int i = 0;
      while (i < 10) 
      {
        Console.WriteLine(i);
        i++;
        if (i == 4) 
        {
          break;
        }
      }  
 

Continue Example

int i = 0;
      while (i < 10) 
      {
        if (i == 4) 
        {
          i++;
          continue;
        }
        Console.WriteLine(i);
        i++;
      }  

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

An array element can be accessed by using its index number.

This statement accesses the value of the first element in cars :

Example

string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      Console.WriteLine(cars[0]);
     / / Outputs Volvo 
 
Recall that array indexes begin at 0: The first element is [0]. The second element is [1], and so on.

Change an Array Element

To modify an individual element’s value, consult the index number:

Example

cars[0] = “Opel”;

Example

      string [ ] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      cars[0] = “Opel”;
      Console.WriteLine(cars[0]);
     / / Now outputs Opel instead of Volvo

Array Length

To find out how many elements an array has, utilize the Length property:

Example

string[ ] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      Console.WriteLine(cars.Length);
   // outputs 4

Other Ways to Create an Array

If you know anything about C#, you’ve probably seen arrays made with the new keyword as well as arrays with a size provided. An array can be created in C# in a few different ways:
 
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right away 
string[] cars = new string[4] {“Volvo”, “BMW”, “Ford”, “Mazda”};
// Create an array of four elements without specifying the size
string[ ] cars = new string[] {“Volvo”, “BMW”, “Ford”, “Mazda”};
// Create an array of four elements, omitting the new keyword, and without specifying the size
string[ ] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
 
Which option you select is entirely up to you. Since the last choice is quicker and easier to comprehend, we will frequently use it throughout our course.


You must, however, use the new keyword if you declare an array and initialize it afterwards:
//Declare an array
string[] cars;
// Add values, using new
cars = new string[] {“Volvo”, “BMW”, “Ford”};
//Add values without using new (this will cause an error)
cars={“Volvo”,“BMW”,“Ford”};

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

string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      for (int i = 0; i < cars.Length; i++)
      {
        Console.WriteLine(cars[i]);
      }

The foreach Loop

Additionally, there is a foreach loop that can only be used to iterate through the items of an array:

Syntax

foreach (type variableName in arrayName)
{
   //code block to be executed
}
Using a foreach loop, the example that follows outputs every member in the Cars array:

Example

      string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      foreach (string i in cars) 
      {
        Console.WriteLine(i);
      }

The previous example might be understood as follows: print the value of i, for each string element (named i, as in index) in Cars.

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

Numerous array methods exist, such as Sort(), which can arrange an array either alphabetically or ascendingly:

Example

// sort a string

string [ ] cars = { “Volvo”, “BMW”, “Ford”, “Mazda};
Array.Sort(cars);
foreach (string i in cars)
{  
Console.WriteLine(i);
}
 
// Sort an int 
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}

System.Linq Namespace

The System has more helpful array functions including Min, Max,  Sum, and System.Linq namespace:

Example

using System;
using System.Linq;
namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] myNumbers = {5, 1, 8, 9};
      Console.WriteLine(myNumbers.Max());  // largest value
      Console.WriteLine(myNumbers.Min());  // smallest value
      Console.WriteLine(myNumbers.Sum());  // sum of myNumbers
    }
  }
}
In a subsequent chapter, there will be more information regarding different namespaces.

Multidimensional Arrays

Arrays, also called single dimension arrays, were covered in the preceding chapter. These are excellent and will come in handy while writing C# code. However, if you wish to store data as a tabular form, like a table with rows and columns, you need to get familiar with multidimensional arrays. An array of arrays is essentially what a multidimensional array is. An array’s dimensions are infinite. Two-dimensional arrays are the most widely used (2D).

Two-Dimensional Arrays

Add each array inside a set of curly braces to form a 2D array. Then, place a comma (,) between the square brackets:

Example

int[ , ] numbers ={ {1, 4, 2}, { 3, 6 , 8 } }
It’s useful to know that the array is two-dimensional because of the single comma [,]. There would be two commas in a three-dimensional array: int[,,].  
numbers now consists of two arrays as its constituent members. Three elements make up the first array element (1, 4, and 2), while three elements make up the second array element (3, 6, and 8). Consider the array as a table with rows and columns to see it:

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

      int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
      Console.WriteLine(numbers[0, 2]);
 
Keep in mind that: Array indexes begin at 0: The first element is [0]. The second element is [1], and so on.

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

      int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
      numbers[0, 0] = 5; //Change value to 5
      Console.WriteLine(numbers[0, 0]); // Outputs 5 instead of 1

Loop Through a 2D Array

A foreach loop makes it simple to iterate over the items of a two-dimensional array:

Example

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
    
      foreach (int i in numbers)
      {
        Console.WriteLine(i);
      } 
A for loop can also be employed. One loop is required for each dimension of a multidimensional array.


Notably, we must provide the number of times the loop should execute using GetLength() rather than Length:

Example

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
    
      for (int i = 0; i < numbers.GetLength(0); i++) 
      {  
        for (int j = 0; j < numbers.GetLength(1); j++) 
        {  
          Console.WriteLine(numbers[i, j]);  
        }  
      }