Passing arrays to methods. Examples of passing arrays of base types. Passing arrays, structures, classes, enumerations to methods. Passing two-dimensional arrays to methods. Returning the array from method

Passing arrays to methods. Examples of passing arrays of base types. Passing arrays of structures, classes, enumerations to methods. Passing two-dimensional arrays to methods. Returning the array from method


Contents


1. How to pass an array to a method? What is the general form of passing a one-dimensional array to a method?

The general form of passing a one-dimensional array to a method is as follows:

access return_type MethodName(type[] parameterName)
{
  // ...
}

where

  • access – access modifier (public, protected, private);
  • return_type – the type returned by the method;
  • MethodName – method name;
  • type – the type of array that is passed to the method;
  • parameterName – the name of the array, which is the formal parameter of the MethodName method.

 

2. An example of passing an array of integers (ulong) to a method

The example demonstrates the ReverseArray method, which reverses an array of ulong type numbers. The method receives the ulong type items array.

// a method that gets an array of items and reverses it
public void ReverseArray(ulong[] items)
{
  ulong t;

  // array reversing
  for (int i = 0; i < items.Length / 2; i++)
  {
    t = items[i];
    items[i] = items[items.Length - i - 1];
    items[items.Length - i - 1] = t;
  }

  return;
}

Using the method in other program code may be as follows:

ulong[] Array = { 2, 3, 1, 2, 8, 5, 6, 100 };
ReverseArray(Array); // Array = { 100, 6, 5, 8, 2, 1, 3, 2 }

 

3. An example of passing to a method an array of double numbers

Implemented a method that receives as a parameter an array of double type. Method returns the sum of the elements of the array.

public double SumDoubleArray(double[] items)
{
  double sum = 0;
  for (int i = 0; i < items.Length; i++)
    sum += items[i];
  return sum;
}

Using the method in other program code may be as follows:

double[] Array = { 3.3, 2.2, 1.1, 7.7, 8.8 };
double sum;
sum = SumDoubleArray(Array); // sum = 23.1

 

4. An example of passing a one-dimensional array of structures to a method

The Country structure is given, describing country information

// structure that contains information about the country
struct Country
{
  public string Name; // the name of the country
  public ulong Population; // population
  public string Capital; // name of the capital
  public double Area; // area, in square kilometers
}

The implementation of the MaxPopulation() method, which determines the country with the largest population. The method gets an array of Country structures.

// method that receives an array of structures of type Country
// the method returns a structure that contains information about the country with the largest population
public Country MaxPopulation(Country[] countries)
{
  int i;
  int numMax;
  double maxPopulation;

  if (countries.Length == 0)
  {
    Console.WriteLine("The list of countries is not specified");
    return new Country();
  }

  maxPopulation = countries[0].Population;
  numMax = 0;

  //
  for (i = 1; i < countries.Length; i++)
    if (countries[i].Population > maxPopulation)
    {
      maxPopulation = countries[i].Population;
      numMax = i;
    }

  return countries[numMax];
}

Demonstration of calling MaxPopulation() from another program code

Country[] countries = new Country[3]; // allocate memory for three structures of Country type
Country cn;

countries[0].Name = "Ghana";
countries[0].Capital = "Accra";
countries[0].Area = 238537.0;
countries[0].Population = 25199609;

countries[1].Name = "Republic of South Africa";
countries[1].Capital = "Pretoria";
countries[1].Population = 54956900;
countries[1].Area = 1219912.0;

countries[2].Name = "Madagascar";
countries[2].Capital = "Antananarivo";
countries[2].Population = 23812681;
countries[2].Area = 587041.0;

// вызов метода MaxPopulation(), передача массива структур в метод
cn = MaxPopulation(countries); // cn.Name = "Republic of South Africa"

 

5. An example of passing a one-dimensional array of classes to a method

The Cylinder class that implements the cylinder is set

// a class that implements a cylinder
class Cylinder
{
  double r;
  double h;

  // constructors
  public Cylinder()
  {
    r = 1; h = 1;
  }

  public Cylinder(double _r, double _h)
  {
    r = _r;
    h = _h;
  }

  // access methods
  public void Set(double _r, double _h)
  {
    r = _r;
    h = _h;
  }

  public void Get(out double _r, out double _h)
  {
    _r = r;
    _h = h;
  }

  // a method, which returns the volume of the cylinder
  public double Volume()
  {
    return 3.1415 * r * r * h;
  }
}

An implementation of the GetMaxVolumeCylinder() method, receiving a Cylinder array. The method returns the ordinal number of the element of the array (cylinder), which has the largest volume

// a method that receives an array of classes of type Cylinder and determines the number of the cylinder with the largest volume
int GetMaxVolumeCylinder(Cylinder[] cylinders)
{
  double maxV = cylinders[0].Volume();
  int maxN = 0;

  for (int i=1; i<cylinders.Length; i++)
    if (maxV < cylinders[i].Volume())
    {
      maxV = cylinders[i].Volume();
      maxN = i;
    }

  return maxN;
}

Using the GetMaxVolumeCylinder() method in another method

Cylinder[] cl; // reference to an array of classes of type Cylinder
cl = new Cylinder[3]; // memory allocation for 3 references to type Cylinder

// allocate memory for each element of a Cylinder array
for (int i = 0; i < cl.Length; i++)
  cl[i] = new Cylinder();

//
cl[0].Set(2, 3.5);
cl[1].Set(1.5, 2.8);
cl[2].Set(3, 4.4);

int num = GetMaxVolumeCylinder(cl); // num = 2

 

6. An example of passing a one-dimensional array of enumerations to a method

The structure of DayWeek, which determines the day of the week, is given

// days of the week
enum DayWeek
{
  Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun
}

Below is the GetDayOff() method, which gets an array of DayWeek type as a parameter. The method determines the number of days off (Saturday, Sunday) in the DayWeek array.

// method that determines the number of days off in the mn array
int GetDayOff(DayWeek[] mn)
{
  int nDayOff = 0;

  for (int i=0; i<mn.Length; i++)
  {
    if (mn[i] == DayWeek.Sat) nDayOff++;
    if (mn[i] == DayWeek.Sun) nDayOff++;
  }

  return nDayOff;
}

Using the GetDayOff() method from another program code may be as follows:

// array of DayWeek type
DayWeek[] dw = new DayWeek[5];

// filling with values the array dw
dw[0] = DayWeek.Sun; // day off
dw[1] = DayWeek.Fri;
dw[2] = DayWeek.Mon;
dw[3] = DayWeek.Sat; // day off
dw[4] = DayWeek.Tue;

int nDayOff;
nDayOff = GetDayOff(dw); // nDayOff = 2

 

7. An example of passing a two-dimensional array of integers (int) numbers to a method

The example demonstrates passing a two-dimensional array to the Sum() method. As parameters, the Sum() method gets:

  • a two-dimensional array of integers named mn;
  • number of rows m in the array;
  • number of columns n in array.

The method calculates the sum of the elements of a two-dimensional array.

// the method gets a two-dimensional array of integers
// parameters m, n - the number of rows and columns in the array
int Sum(int[,] mn, int m, int n)
{
  int sum = 0;

  for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
      sum += mn[i,j];

  return sum;
}

In order to correctly access the elements of an array, the method needs to pass the number of rows m and columns n. Using the Sum() method in another program code

// array arr declaration
int[,] arr = new int[3, 4];

// filling the array with arbitrary values
for (int i = 0; i < 3; i++)
  for (int j = 0; j < 4; j++)
    arr[i, j] = i + j;

// Call the Sum() method to which the arr array is passed
int s = Sum(arr, 3, 4); // sum = 30

 

8. An example of passing a two-dimensional array of classes to a method

Let a class be given that implements the color and transparency of a pixel on the screen. The class declaration is as follows.

// a class that implements the color and transparency of a pixel on the screen
class ColorPixel
{
  int color;
  int transp; // transparency in %

  // constructors
  public ColorPixel()
  {
    color = transp = 0;
  }

  public ColorPixel(int _color, int _transp)
  {
    color = _color;
    transp = _transp;
  }

  // access methods
  public int GetColor() { return color; }
  public int GetTransp() { return transp; }
  public void Set(int _color, int _transp)
  {
    color = _color;
    transp = _transp;
  }
}

The declaration of the SetArrayColor() method, which sets the color and transparency in a two-dimensional array of ColorPixel type classes, is demonstrated.

// set new values of color and transparency in the cp array
void SetArrayColor(int m, int n, ColorPixel[,] cp, int _color, int _transp)
{
  for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
      cp[i, j].Set(_color, _transp);
  return;
}

The use of the method in other program code may be as follows

// create a new array of classes ColorPixel
int m = 3, n = 5;
ColorPixel[,] CP = new ColorPixel[m, n]; // allocate memory for an array of references

// allocate memory for every item of the array
for (int i = 0; i < m; i++)
  for (int j = 0; j < n; j++)
    CP[i, j] = new ColorPixel();

// set a specific color value of 5 and transparency 50 % in all cells of the array
SetArrayColor(m, n, CP, 5, 50);

 

9. Example of returning a one-dimensional array of integers (int) from a method

A method that returns an array of integers (int []) is implemented. The method fills the array elements with values that are the squares of the positions (indices) of the array. The method accepts as an input parameter the size of the array n.

// method that generates a one-dimensional array of integers
// array items are squares of array positions
public int[] GetArray(int n)
{
  int[] temp = new int[n]; // allocate memory for the array

  // fill the array with values
  for (int i = 0; i < n; i++)
    temp[i] = i * i;

  return temp;
}

Calling a method from another program code may be as follows

int[] A; // declare a reference to array A
A = GetArray(5); // A = { 0, 1, 4, 9, 16 }

 

10. An example of returning a two-dimensional array of double type from a method

The return of a two-dimensional array from a method is demonstrated. The GetDoubleArray() method gets the size of the m * n array as an input parameter. The method returns an array.

// method that generates a two-dimensional array of integers
// array size m * n
public double[,] GetDoubleArray(int m, int n)
{
  // create a new array and allocate memory for it
  double[,] temp = new double[m, n];

  // filling the array with values
  for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
      temp[i, j] = j + i;

  return temp;
}

Using the GetDoubleArray() method in other program code

double[,] D;
D = GetDoubleArray(5, 6);
double x;
x = D[1, 3]; // x = 4.0
x = D[2, 5]; // x = 7.0
x = D[0, 0]; // x = 0.0

 

11. An example of returning a two-dimensional array of classes from a method

Let a class that implements a symbol of type char be given. The class has an internal variable, a constructor, and methods that determine the symbol’s belonging to a certain category.

// class that implements a symbol
class Char
{
  char symbol; // internal variable

  // constructor
  public Char(char _symbol) { symbol = _symbol; }

  // access methods
  public void Set(char _symbol) { symbol = _symbol; }
  public char Get() { return symbol; }

  // additional methods
  // determines whether a symbol of type Char is a digit
  public bool IsNumber()
  {
    if ((symbol >= '0') && (symbol <= '9'))
      return true;
    return false;
  }

  // determines whether a symbol of type Char is a Latin letter
  public bool IsLetter()
  {
    if ((symbol >= 'a') && (symbol <= 'z')) return true;
    if ((symbol >= 'A') && (symbol <= 'Z')) return true;
    return false;
  }

  // determines if there is a Char symbol with a space
  public bool IsSpace()
  {
    return symbol == ' ';
  }
}

An implementation of the GetArrayChar() method that generates (returns) a two-dimensional array of Char objects

// method that returns a two-dimensional array of Char classes
// method generates arbitrary characters
// m, n - array dimension
Char[,] GetArrayChar(int m, int n)
{
  Char[,] tempArray = new Char[m, n]; // allocate memory for an array of Char references
  int value;

  // form an array termpArray
  for (int i=0; i<m; i++)
    for (int j=0; j<n; j++)
    {
      value = i + j; // the value that will be stored in the array
      if (value > 255) value -= 255;

      // allocate memory for array item + initialize with value
      tempArray[i, j] = new Char((char)value);
    }

  return tempArray;
}

Demonstration of calling GetArrayChar() from another program code

// create a new array of Char classes
int m = 3, n = 5;
Char[,] Array; // declare an object of type two-dimensional array Char

// call the method that will form the Array array
Array = GetArrayChar(8, 9);

 

12. An example of passing a two-dimensional stepped array to a method

The example demonstrates the passing to the method and returning from the method a two-dimensional stepped array of integer values.
The CopyIntArray() method receives as input parameters the number of rows m in the stepped array A and same stepped array A. The method returns a stepped array B, which is a copy of array A. The stepped array B is located in a different area of memory.

// the method copies the input stepped array to another stepped array
// m - number of rows in a stepped array
// the result is placed into another array, which is located in a different area of memory
int[][] CopyIntArray(int m, int[][] A)
{
  // declare another array
  int[][] B = new int[m][]; // allocate memory for references to array strings

  for (int i = 0; i < m; i++)
  {
    // allocate memory for the row with number i
    B[i] = new int[A[i].Length]; // Array[i].Length - number of items in row i

    for (int j = 0; j < A[i].Length; j++)
      B[i][j] = A[i][j];
  }

  return B;
}

Demonstration of using the CopyIntArray() method to copy arrays is as follows

// create a new stepped array
int m = 4; // number of rows in array
int[][] A = new int[4][]; // source array
int[][] B; // the resulting array

// 1. Form the array A
// allocate memory for array A
A[0] = new int[5]; // there are 5 items in row 0
A[1] = new int[3];
A[2] = new int[4];
A[3] = new int[2];

// write arbitrary values to array A
for (int i = 0; i < m; i++)
  for (int j = 0; j < A[i].Length; j++)
    A[i][j] = i + j;

// 2. Call the method, which copies array A into array B
B = CopyIntArray(m, A); // B <= A

// 3. Вывести на экран массив B
for (int i = 0; i < m; i++)
{
  Console.Write("B[{0}] = ", i);
  for (int j = 0; j < B[i].Length; j++)
    Console.Write("{0} ", B[i][j]);
  Console.WriteLine(" ");
}

As a result of executing the above code, the following result will be displayed.

B[0] = 0 1 2 3 4
B[1] = 1 2 3
B[2] = 2 3 4 5
B[3] = 3 4
Press any key to continue . . .


Related topics