C# Study Notes - Arrays

1. Recursion

  • The method calls its own process inside;
  • Core idea: transfer the problem to sub-problems with narrowed scope;
  • Applicability: In the process of solving the problem, the same problem is encountered again;
  • Advantages: Simplify complex problems;
  • Disadvantages: poor performance (too much cpu usage)
  • Note: There is a stack overflow

Two, one-dimensional array

  • Derived from the Array class, a group of variable combinations with the same data type;
  • A spatially continuous data structure;
  • Elements are manipulated by index (the ordinal number of the position).

1. Define an array

  • Declare array
    data type [ ]   ~ array name
  • Initialize the array
    array name = new   ~ datatype[total number of elements];

2. Initialize the array

1>Initialization

  • The initialized element type must be the same as it was declared.
  • After the array is initialized, the default value of the data type is stored in memory:
    – integer is 0
    – non-integer is 0.0
    – char is \0
    – string is null –
    bool is false

2>Initialization + assignment

  • You can assign values ​​to elements while initializing the array;
  • Syntax:
    data type [ ] array name = new   ~ datatype[] {element 1, element 2...};
    eg:
    int[] array01 = new int[] {1, 2, 3, 4, 5};
  • The length of the array can also be filled in [ ] during initialization, but it must be consistent with the total number of assigned elements.

3> Declaration + Assignment

  • Elements can be assigned while the array is declared;
  • Syntax:
    data type [] array name = {element 1, element 2...};
    for example:
    int[] array01 = {1, 2, 3, 4, 5};
  • The number of elements is the array length;
  • The programmer can omit the initialization, but the compiler will still "new data type []" internally;
  • The following writing methods are not supported:
    double[] array03;
    array03 = {1.0, 2.0};

3. Access array elements

1> Access by index

  • Read and write operations can be performed through the index of the array (the serial number of the position);
  • Syntax:
    array name [index]
    For example:
    string[] array = new string[] {"a", "b", "c"};
    Console.WriteLine(array[0]); – get the first element of the array

2> traverse through for

  • Traversal: visit each element in a certain order;
  • The for loop traverses the array elements and outputs them to the console in positive order:
    string[] array = new string[]{"a", "b", "c"};
    for (int i=0; i<array.Length; i++ )
    {        ~~~~~~
          Console.WriteLine(array[i]);
    }
  • The for loop traverses the array elements and outputs them to the console in reverse order:
    string[] array = new string[]{"a", "b", "c"};
    for (int i=array.Length -1 ;i<=0 ;i --)
    {        ~~~~~~
          Console.WriteLine(array[i]);
    }

3> traverse through foreach

  • foreach is a simpler and clearer statement to read array elements;
  • Limitations:
    1. Can only read all elements (the statement itself)
    2. Cannot modify elements
    3. Can only traverse collection objects that implement the Ienumberable interface
  • Syntax:
    foreach(element type   ~ variable name   ~  in   ~  array name)
    {        ~~~~~~
          The variable name refers to each element in the array
    }

4. Params keyword

  • If there is a method whose parameter is an array type, using the params keyword can make the number of parameters passed into the method variable, so that there is no need to explicitly declare the size of the array, but the types of the parameters must be consistent;
  • If you use the params keyword, you can use an array as a parameter;
  • A method can only use one params keyword, and the params keyword can only modify the last parameter of the method;
using System;

namespace Day05
{
    
    
    class Program
    {
    
    
        //定义整数相加的方法
        
        //当类型确定  个数不确定的情形  用数组
        //params 参数数组
        //对于方法内部而言:就是一个普通数组
        //对于方法外部(调用者)而言:
        //可以传递数组
        //可以传递一组数据类型相同的变量集合
        //甚至可以不传递参数
        //作用:简化调用者调用方法的代码
        private static int Add(params int[] array)
        {
    
    
            int sum = 0;
            foreach (var item in array)
            {
    
    
                sum += item;
            }
            return sum;
        }

        static void Main()
        {
    
    
            int result01 = Add(new int[] {
    
    1,3,5,787,45 });
            int result02 = Add(1, 3, 4, 56, 78);
            int result03 = Add();
        }

    }  
}

5. Common methods and properties

  • Array length: Array name.Length
    Clear element value: Array.Clear
    Copy element: Array.copy         ~~~~~~~       Array name.CopyTo
    clone: ​​Array name.Clone
    Find element: Array.IndesOf         ~~~~~~~       Array.LastIndexOf
    Sort: Array.Sort
    Reverse: Array.Reverse

Three, multidimensional array

1. Rectangular array

  • array with two or more indices
  • Syntax:
    –declare + initialize
    datatype[ , ]   ~ ArrayName = new   ~ data type [rows, columns];
    – initialization + assignment
    array name = new data type [ , ] { {element 1, element 2…}, {element 3, element 4…}};
    – read and write element
    array name[ row index, column index]
  • The for loop traverses the array elements and outputs them to the console in tabular form:
//获取行数
for (int i = 0; i < array.GetLength(0); i++)
{
    
    //获取列数
    for (int j = 0; j < array.GetLength(1); j++)
   {
    
    
       Console.Write(array[i,j] + "\t");
   }
        Console.WriteLine();//换行
}

2. Sawtooth array (staggered array)

  • The size of each row in the array can be different;
  • When creating a jagged array, you must declare the number of rows in the array. The arrays stored in each row must be created separately before you can assign values ​​to the elements of the arrays within those arrays.
  • Syntax:
    –declare + initialize
    datatype[ ][ ]   ~ ArrayName = new   ~ datatype[number of rows][];
using System;

namespace Day05
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //交错数组  参数数组
            //交错数组:每个元素都为一维数组,分布通常想想为“不规则的表格”
            int[][] array;//null
            //创建具有4个元素的交错数组
            array = new int[4][];
            //创建一维数组  赋值给 交错数组的第一个元素
            array[0] = new int[3];

            array[1] = new int[5];
            array[2] = new int[4];
            array[3] = new int[1];
            //将1赋值给交错数组的第一个元素的  第一个元素
            array[0][0] = 1;

            array[1][2] = 2;
            array[2][1] = 4;
			//获取交错数组的每一个元素
            foreach (int[] item in array)
            {
    
    //获取交错数组每一个元素 中的每一个元素
                foreach (int element in item)
                {
    
    
                    Console.WriteLine(element);
                }
            }
            //array.Length 交错数组元素数(理解为:行数)
            for (int i = 0; i < array.Length; i++)
            {
    
    //获取第i个元素的长度
                for (int j = 0; j < array[i].Length; j++)
                {
    
    //获取第i个元素的  第j个元素
                    Console.Write(array[i][j] + "\t");
                }
                Console.WriteLine();
            }

        }
    }
}

Four. Summary

  • An array is a collection of objects that can be accessed through an index, and the stored objects have the same type;
  • You can use the for loop to traverse the array, and use the counter of the number of loops as the index value to access the array;
  • Using foreach to traverse arrays (or other collections) does not need to record index values;
  • The array can be initialized while creating the array by writing the initial value in braces { };
  • The params keyword can pass a variable number of parameters when calling the method. The types of these parameters must be consistent, and the method treats these parameters as an array;
  • The Array class contains methods through which operations such as searching, sorting, etc. can be performed on the array.
  • A rectangular array is a multidimensional array, while a jagged array is an array of arrays.

Guess you like

Origin blog.csdn.net/Lcl_huolitianji/article/details/119190280