Lesson # 9. A single-dimensional array and Generic method, Classes

Using Generic method and classes while working with Single Dimension Arrays.

Labs and tasks

Lab 1. Using a Generic method and Foreach loop to work with arrays
  
To do: Create a class named MyFuncs and a generic function named PrintArr, which outputs an array of any type and any length to the console window. Use foreach loop to iterate over the elements (to print out) of an array. Call the method twice: the first one — for an array of integer type, the second — for an array of double type.

Expected output:

The integer array:
1 6 2 7 5
The double array:
1.2   6.4   2.1   7.5

  

[Solution and Project name: Lesson_9Lab1, file name L9Lab1.cs]

✍ How to do:

  • Create a Console Application with a name Lesson_9Lab1.
  • In the Solution Explorer window find a Program.cs file and rename it into L9Lab1.cs.
  • In order not to print always the class Console, we can include its declaration right at the beginning of the editor window:
  • ...
    using static System.Console;
    ...
  • We are going to add a new class. Place your cursor immediately after the close brace of the L9Lab1 class. Create a new class with a name MyFuncs. To make it accessible in all the project’s classes and namespaces we’re going to use the keyword public:
  • public static class MyFuncs
        {
        }
    
  • Within the MyFuncs class create a method called PrintArr, which will output an array. To make the method accessible we’re going to use the keyword public:
  • public static void PrintArr<T>(this T[] arr)
       {
       }
    
    Note that T is used to handle an array of any type. this keyword means that we extend this type by the method.
    Static keyword means that we can access that method directly by the PrintArr class itself, we do not have to create an object to access a static member.
  • Place your cursor immediately after the open curly brace of the PrintArr method. Now, we’re going to print out the array’s elements. We have to use foreach loop:
  • foreach (var x in arr)
      {
         Console.Write($"{x} ");
      }
    
    foreach loop is usually used to iterate over the elements of an array of any length. The variable x accepts the values of each element of the array one by one inside the loop. And we output it to the console window.
  • Within the Main() function create a single-dimensional array of integers with the name arr1 and assign the values to its elements:
  • static void Main(string[] args)
       {
       Console.WriteLine("The integer array:");
       int[] arr1 = new int[] { 1, 6, 2, 7, 5 };
    ...
    
    In order to allocate memory for the object (instance) we need to use the new operator. After, we can access object’s members (fields and methods) using dot notation.
  • After, call the PrintArr method using dot notation:
  • ...
    arr1.PrintArr();
    ...
    
    dot notation is usually used to handle objects. arr1 is an instance of the class of array object.
  • After avoking the method, you need to create a single-dimensional array of doubles with the name arr2 and assign the values to its elements. Call this method:
  • ...
      Console.WriteLine("The double array:");
      double[] arr2 = { 1.2, 6.4, 2.1, 7.5 };
      arr2.PrintArr();
    ...
    
  • Run the program by pressing CTRL+F5 to see the output.
  • Save the solution and upload the file to the moodle system.


Task 1:

To do: Open the previous Lab and within the code create one more function which outputs the elements with even indexes of the array of any length and any type.

Note: Create a function named PrintEvenIndexes to output the array’s elements with even indexes. Remember that indexes start with zero. The function must be placed inside the MyFuncs class and it has to be Generic (<T>, remember a theory of generic). Don’t forget about the keyword this.
     
 
Expected output:

The integer array:
1 6 2 7 5
The elements with even indexes:
1 2 5
The double array:
1,2  6,4  2,1  7,5  8,1
The elements with even indexes:
1,2  2,1  8,1

[Solution and Project name: Lesson_9Task1, file name L9Task1.cs]

Lab 2. Using a class file and method to work with arrays
  
To do: Create a class named Calculator and a function named Add that takes a varying number of arguments and outputs an addition of them to the console window. Use foreach loop to iterate over the elements (to print out) of an array. Call the method thrice: the first one — with two parameters, the second — with three parameters, the third — with an integer array.

The result example:

the result with two parameters is (1, 2): 3
the result with three parameters is (1, 2, 3): 6
the result with an array is (1, 2, 3, 4, 5): 15

  

[Solution and Project name: Lesson_9Lab2, files’ names L9Lab2.cs and Calculator.cs]

✍ How to do:

  • Create a Console Application with a name Lesson_9Lab2. Rename the program.cs file into L9Lab2.cs.
  • We are going to create a Calculator class. Add a new class file to the project. Give it a name Calculator.
  • Within the opened file-code you need to add a public keyword to make the class accessible in all the project’s classes and namespaces.
  •  public class Calculator
        {
        }
    
  • Create a method called Add that takes a varying number of arguments. Also, use a keyword public:
  • public int Add(params int[] numbers)
            {
    
            }
    
    We have a public Add method which returns int value (integer). The method has params keyword (to make it able to pass a varying number of parameters), and integer array with the name numbers.
  • So we have an integer array and we want to have an addition of all the numbers in that array and return the result (a sum).
  • First, we create a variable called sum and set it to 0:
  • var sum = 0;
    
  • After, we use a foreach loop to iterate over the numbers and simply add every number to the sum:
  • foreach (var number in numbers)
                {
                    sum += number;
                }
    
  • And finally, we return sum:
  • return sum;
    
  • Go back to the program (L9Lab2.cs file) in the Solution Explorer window and create an instance of the Calculator class within the Main class code:
  • static void Main(string[] args)
            {
                var calculator = new Calculator();
            }
    
    In order to allocate memory for the object (instance) we need to use the new operator. After, we can access object’s members (fields and methods) using dot notation.
  • After, we can call the Add method passing two numbers as arguments, and simply display the result on the console:
  • Console.WriteLine($"the result with two parameters is (1, 2): {calculator.Add(1, 2)}"); 
    
  • Run the program by pressing CTRL+F5 to see the output.
  • Then we can pass three parameters or four (it can pass a varying number of parameters):
  • Console.WriteLine($"the result with three parameters is (1, 2, 3): {calculator.Add(1, 2, 3)}");
    
  • Run the program again.
  • We can also call this method using array notation (we can pass a new integer array):
  • Console.WriteLine($"the result with array is (1, 2, 3, 4, 5): {calculator.Add(new int[]{1,2,3,4,5})}");
    
    It’s easier to pass all the parameters without the need to create an integer array and that’s why we use the params keyword.
  • Run the program. Save the solution and upload the file to the moodle system.

Task 2:

To do: Create a method (function) that finds a minimum of a sequence of integer numbers and sets the value of the found minimum element to 0 value. Function must return a new array with zeros instead of minimum values. Call the method twice: with three integers and with an array of integers. It is not allowed to use standard function min.

Note 1: Create a class named Mimimum and a function named FindMin within the class. The function returns an array, that’s why you must use the signature with return type int[]:

public int[] FindMin(params int[] numbers)

Note 2: Within the method, you must use foreach loop and for loop:
1. foreach loop which iterates over the numbers and finds a minimum of them (remember how to find minimum here (lab 3), but use foreach loop).
2. for loop which iterates over the numbers and finds the value that equals to the minimum and set it to 0.
  
Note 3: The function returns an array, that’s why you must assign the result of the function to an array variable. After the calling of the function you have to print out the values of the array elements:

int[] result1 = minimum.FindMin(5, 3, 6);
foreach (var i in result1)
            {
                ...
            }

  
Expected output:

the result with the three parameters (5, 3, 6) is:
5
0
6

the result with the array of integers ( 5, 3, 3, 6, 5 ) is:
5
0
0
6
5

  
[Solution and Project name: Lesson_9Task2, files’ names L9Task2.cs and Minimum.cs]