Lesson # 7. Creating and Using Single-Dimensional Arrays

Programming on c sharp in Microsoft Visual Studio. Creating and Using Single-Dimensional Arrays.

Lesson # 7. Theory

Lecture in pdf format
  
Arrays in Visual C# have the following features:

  • Every element in the array contains a value.
  • Arrays are zero-indexed, that is, the first item in the array is element 0.
  • The size of an array is the total number of elements that it can contain.
  • Arrays can be single-dimensional, multidimensional, or jagged.
  • The rank of an array is the number of dimensions in the array.

Creating and Using Single-Dimensional Arrays

The following code example shows how to create a single-dimensional array of integers with elements zero through nine:

int[] arrayName = new int[10];

Accessing Data in an Array

The following code example uses an index to access the element at index two:

//Accessing Data by Index
 int[] oldNumbers = { 1, 2, 3, 4, 5 };
//number will contain the value 3
int number = oldNumbers[2];
Note: Arrays are zero-indexed, so the first element in any dimension in an array is at index zero. The last element in a dimension is at index N-1, where N is the size of the dimension. If you attempt to access an element outside this range, the CLR throws an IndexOutOfRangeException exception.

The following code example shows how to use a for loop to iterate through an array:

//Iterating Over an Array
 int[] oldNumbers = { 1, 2, 3, 4, 5 };
 for (int i = 0; i < oldNumbers.Length; i++)
 {
     int number = oldNumbers[i];
     ...
 }

Samples

    public static void Main()
    { 
    //We declare the array variable in the same way as we previously declared variables of other types.
    //The type of the array of numbers is int[]. Similarly, there are types string[], double[], etc.
     
    	int[] array;
    	int number;
     
    //We initialize the variable array - the new array with a length 3. 
     
    	array = new int[3];
    	number = 10;
     
    // We get access to the elements of the array
    	array[0] = 1;
    	array[1] = 2;
    	array[2] = 3;
     
    //An array, like other types, has its own properties and methods
    	Console.WriteLine(array.Length); //Выведет 3
     
    //Note that array.ToString() has not good results:	
            Console.WriteLine(array.ToString()); // "System.Int32[]" will be outputted
     
    //The next code will arise an exception - going beyond array boundaries
    	Console.WriteLine(array[100]);
     
    	var array2 = new[] { 1, 2, 3 };
     
    //how to use a for loop to iterate through an array:
    	for (int i = 0; i < array2.Length; i++)
    		Console.WriteLine($"{array2[i] }");
     
    // but it is better to use foreach operator 	
    //foreach is recommended for c#
     
    	foreach (var e in array2)
    		Console.WriteLine(e);
     
    //But sometimes, in a case when assigning the values of an array, the foreach operator will be not suitable.
    	for (int i = 0; i < array2.Length; i++)
    		array2[i] = 2 * i;
     
    }

    Random function

    • Let’s look at the example of the initializing the array of five elements of byte type with random values:
    • 1. Instantiate random number generator using system-supplied value as seed:

      var rand = new Random();

      2. Generate and display 5 random byte (integer) values:

      var bytes = new byte[5];
      rand.NextBytes(bytes);
      Console.WriteLine("Five random byte values:");
      // output:
      foreach (byte byteValue in bytes)
          Console.Write("{0, 5}", byteValue);
      Console.WriteLine();

    Labs and tasks

    Lab 1. Number of odd elements in an array

    To do: An array of integers is given (the values of its elements: -1, -2, 3, 4, 5, 6, 7). Output the array using a function. Create one more function to calculate the number of odd elements in this array, as well as the number of positive elements in it.

    Note 1: Create a function named Print to output the array’s elements.

    Note: Create a function CountOddPositive with foreach loop and if statements to check to see if an element is odd or positive.

    Expected output:

    Array: 
    -1, -2, 3, 4, 5, 6, 7 
    number of odd elements: 5, number of positive elements 5.
    

    [Solution and Project name: Lesson_7Lab1, file name L7Lab1.cs]

    🎦
    ✍ How to do:

    • Create Console Application with the name Lesson_7Lab1.
    • In the Solution Explorer window find a file Program.cs and rename it into L7Lab1.cs.
    • In order not to print always the class Console, we can include its declaring right at the beginning of the editor window:
    • ...
      using static System.Console;
      ...
    • Within the Main() function create a single-dimensional array of integers with the name a and assign the values for its elements:
    • ...
      int[] a = new int[] { -1, -2, 3, 4, 5, 6, 7 };
      ...
      
    • Under the Main() function create a method with the name Print with one parameter: arr parameter of int type to accept the values of the array elements. The function doesn’t return any value (void):
    • static void Print(int[] arr)
              {
                  WriteLine("Array:");
                  foreach (var x in arr)
                      Write(x + " ");
                  WriteLine();
              }
      

    • Within the Main function call the method to output the elements. And run the code to see the output.
    • ...
      Print(a);
    • To collapse the code of the method for a while you can use Ctrl+M (twice). To expand it again use the same shortcut snippet Ctrl+M (twice).
    • Now you have to create the CountOddPositive function which accepts the array as a parameter and has two more ref parameters to pass the values of the counters for positive and odd elements (countPos and countOdd) :
    • ...
      static void CountOddPositive( int[] arr, ref int countOdd, ref int countPos)
         {
      
         }
      ...
      
    • Within the function use foreach loop to iterate through the array and check the elements:
    • ...
      static void CountOddPositive( int[] arr, ref int countOdd, ref int countPos)
         {
      foreach (var x in arr)
                  {
                      if (x % 2 != 0)
                          countOdd++;
                      if (x > 0)
                          countPos++;
                  }
         }
      ...
      
    • Ref parameters have to be initialized before the calling of the method. Let’s do it in the Main function:
    • ...
      int countPos = 0;
      int countOdd = 0;
      ...
      
    • After this, call this method within the Main function, passing the array to the CountOddPositive function as one of the arguments:
    • ...
      CountOddPositive(a, ref countPos, ref countOdd);
      ...
      
    • Output the result:
    • ...
      WriteLine($"number of odd elements: {countOdd}, number of positive elements {countOdd}.");
       ...
      
    • Run the program by pressing CTRL+F5 to see the output.

    Task 1:

    To do: An array of doubles is given (the values of its elements: 1.1, -2.3, 3.7, 4.1, 5.6, 6.1, 7.1).
    1. Create a function to print the array.
    2. Create one more function to find and print a minimum and maximum elements of this array. Note, that it is not allowed to use the standard min and max functions.
      
    Note 1: To remember how to find a minimum and maximum, take a look at lab 4 of 5-th lesson.
     
    Note 2: Create a function named Print to output the array’s elements.
     
    Note 3: Create a function FindMaxMin with foreach loop and if statements to find maximum and minimum elements. The signature of the function should look like this:

    static void FindMaxMin(double[] arr, ref double max, ref double min)
      {
      }

         

    Expected output:

    Array: 
    1.1  -2.3  3.7  4.1  5.6  6.1  7.1 
    maximum element is: 7.1, minimum element is: -2.3
    

    [Solution and Project name: Lesson_7Task1, file name L7Task1.cs]

    Lab 2. Random

    To do:
    1. Create a function with the name FillRandomArray to fill an array of 10 elements with random numbers in the range from -10 to 15.
    2. Create another function PrintArray to output the array.
    3. Create the function DivisibleBy3 to count and output the elements divisible by 3.

    Expected output:

    Array: 
    -1, -2, 3, 4, 5, 6, 7, 12, 9, 10 
    elements divisible by 3: 
    3  6  12  9
    number of elements divisible by 3: 4
    

    [Solution and Project name: Lesson_7Lab2, file name L7Lab2.cs]

    ✍ How to do:

    • Create Console Application with the name Lesson_7Lab2. In the Solution Explorer window find a file Program.cs and rename it into L7Lab2.cs.
    • In order not to print always the class Console, we can include its declaring right at the beginning of the editor window:
    • ...
      using static System.Console;
      ...
    • Within the Main() function declare a single-dimensional array with a length of 10 elements:
    • ...
      int[] arr = new int[10];
      ...
      
    • Under the Main() function create a method with the name FillRandomArray with three parameters: arr parameter of int type to accept the empty array, minValue parameter of int type to set the lower bound for the function Random, and maxValue parameter of int type to set the upper bound for the function Random. The function doesn’t return any value (void):
    • ...
      static void FillRandomArray(int[] arr, int minValue = -10, int maxValue = 15)
              {
                  //...
              }
      ...
      
    • Within the created function instantiate random number generator using system-supplied value as seed:
    • Random rand = new Random();
      
    • Generate and display random integer values of the array, using the boundaries (parameters minValue and maxValue) :
    • ...
      for (int i = 0; i < arr.Length; i++)
      {
          arr[i] = rand.Next(minValue, maxValue);
      }
      
    • Call this method (FillRandomArray) within the Main function, passing the array as one of the arguments, and boundaries -10 and 15 for the random as it is given in the task:
    • ...
      FillRandomArray(arr, -10, 15);
      ...
      
    • Create a method named PrintArray with one parameter: arr parameter of int type to accept the values of the array elements. The function doesn’t return any value (void) and displays the elements of the array :
    • static void PrintArray(int[] arr)
              {
                  for (int i = 0; i < arr.Length; i++)
                  {
                              Write($"{arr[i]} ");
                  }
              }
      
    • Call this method (PrintArray) within the Main function, passing the array as an argument:
    • PrintArray(arr);
      
    • To collapse the code of the method for a while you can use Ctrl+M (twice). To expand it again use the same shortcut snippet Ctrl+M (twice).
    • Now you have to create the function DivisibleBy3, that looks for the array elements that are divisible by 3 and displays them.
    • static void DivisibleBy3(int[] arr)
              {
                  int counter = 0;
                  WriteLine("elements divisible by 3:");
                  
                  for (int i = 0; i < arr.Length; i++)
                  {
                      if (arr[i] % 3 == 0) {
                          Write($"{arr[i]} ");
                          counter++;
                      }
                  }
                  WriteLine();
                  WriteLine($"number of elements divisible by 3: {counter}");
              }
      
    • Call this method (DivisibleBy3) within the Main function, after calling two previous methods:
    • ...
      DivisibleBy3(arr);
      
    • Run the program by pressing CTRL+F5 to see the output.
    • Add comments with the task and save the project. Download file .cs to the moodle system.

    🎦

    Task 2:

    To do: An array of integers is given (15 elements with random values in the range from 1 to 10). Find if there is an element equal to N in the array (N is inputted). Output «yes» or «no» only once. To find the element use foreach loop.
    1. Create the functions to fill the array and output it’s elements.
    2. Create one more function FindN to find an element equal to N (N is one of the parameters of the function).

    Note 1: To stop a loop iterations the break statement is required:

    foreach (int x in arr) 
                {
                    if (...)
                    {
                        ...
                        break; // exit loop
                    }
                }

     
    Note 2: To check to see if the number was found you can create boolean variable:

    bool f = false;

      
    Expected output:

    Array: 
    9 5 1 3 7 7 8 1 4 4 
    input a number to look for:
    6
    result: no
    
    Array: 
    2 6 2 6 8 1 9 1 7 2 
    input a number to look for:
    2
    result: yes
    

      
    Extra task: Find the index of the found element.

      
    [Solution and Project name: Lesson_7Task2, file name L7Task2.cs]

    🎦

    Task 3:

    To do: An array of doubles is given (10 elements with random values in the range from -5.0 to 5.0).
    1. Create the functions to fill the array and output it’s elements.
    2. Create one more function to calculate and print the sum of triples of adjacent elements: a[1]+a[2]+a[3], a[2]+a[3]+a[4], a[3]+a[4]+a[5], …… , a[8]+a[9]+a[10].
      
    Note 1: To generate double values of the array, using the boundaries:

    //For example, in the range from -20 to 20:
    Random rand = new Random();
    ...
    a[i]=rand.NextDouble() * 40 - 20;

    Note 2: To output doubles with a number of signs after decimal point:

    // two signs after point
    Write("{0:0.00} ",arr[i] ); // e.g. 1.21

      
    Expected output:

    Array: 
    -3,54 0,51 3,79 1,85 -4,11 -2,32 -1,35 -0,78 0,63 4,31 
    sums of the triples:
    0,76 6,15 1,53 -4,59 -7,79 -4,46 -1,50 4,16 
    

      
    [Solution and Project name: Lesson_7Task3, file name L7Task3.cs]