Array of C ා basis

Keywords: Attribute Windows

Array of C ා basis

This paper introduces the array in C ා language, and realizes the program of prime number (bool array) and block game (button array) by the array.

I. array

1. Array overview
  • An array is a combination of data of the same type
  • Array belongs to reference type
  • How to declare a one-dimensional array:
    int [] a1; / / Note: square brackets are written before variable names
    double [] b;
    MyDate [] c;
    The length of an array (the number of elements in the array) cannot be specified when it is declared in C ා language
    Example: int a[5]; / / illegal
2. Array initialization

Array definition is separated from the operation of allocating space and assigning values to array elements.
Example:

/**
* Integer array
**/
int [] a = new int[3]; //Reference type, pointing to a newly applied space
a[0] = 3;
a[1] = 9;
a[2] = 8;


/**
* Object array
**/
MyDate [] dates;
dates = new MyDate[3];
dates[0] = new MyDate(22,7,1976);
dates[1] = new MyDate(2,3,2010);
dates[2] = new MyDate(11,2,2020);
  • initiate static
    While defining an array, space is allocated and assigned to the array elements.
    int [] a ={3,7,4};
    It can also be written as int [] a = new int []{3,7,4};
    Object array:
    MyDate [] dates = {
         new MyDate(22,7,1976),
         new MyDate(2,3,2010),
         new MyDate(11,2,2020);
    }
    Note: a comma can be added at the end. For example: {3, 7, 6,}

  • Default initialization of array elements
    Array is a reference type, its elements are equivalent to the member variables of the class, so once the array is allocated space, each element is implicitly initialized in the same way as the member variables.
    Example:
    (array type is 0, reference type is null)
    int [] a = new int[5]; //a[3] is 0

3. Reference of array element
  • How array elements are referenced
  • index is the subscript of array element, which can be an integer constant or an integer expression.
  • For example: a[3],b[i],c[b* i]
  • Array element subscript starts from 0 and length is n. value range of legal subscript: 0~n-1;
  • Each array has an attribute Length indicating its Length, for example: a.length indicating the Length of array a (number of elements);

foreach statement:
foreach can easily handle elements in an array set.
Such as:
int ages = new int [10];

Foreach (int age in ages) / / ages for array name, age for variable name
{
     //........
}

Note: foreach is read-only traversal

4. Copy array

The Array.Copy method provides the function of copying array elements:
/ / source array
int [] source = {1,2,3,4};
//Target array
int dest = {10,9,8,7,6,5};
//Copy the source.length elements from subscript 0 in the source array to the destination array, and store them from the position of subscript 0
Array.Copy(source,0,dest,0,source.length)

5. Multidimensional array

Two dimensional array example:
int [ , ] a ={{1,2,5},{3,4,0},{5,6,7}};
You can use a.GetLength(0) - dimension 0,
a.GetLength(1) - the first dimension to get the length of each dimension.

6. Interleaved array

The interleaved array in C is an array of arrays
Int [] [] t = New Int [3]; / / 3 represents that the first dimension has three elements, and the second dimension is unknown
t[0] = new int [2];
t[1] = new int [4];
t[2] = new int [3];
The declaration and initialization of multidimensional array in C ා should be carried out from high dimension to low dimension,
Int T1 []] = New Int [] [4]; / / illegal, different from C + +

2, Array sample program

1. Finding prime number by screening method

Important: use bool array
Problem: input a value, find the prime number of the value and output. (prime number has no multiple other than itself)
Idea: build a bool array, initialize the array through a loop (True), and then loop to determine whether each value is a prime number. If not, change the corresponding value in the array to (False). Finally, traverse the array to find out the element whose value is True and output its subscript.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the range to judge");
            int N = int.Parse(Console.ReadLine());//Enter the value range to judge from 1 to n
            bool[] a = new bool[N + 1];//Subscript starts from 0, 1~N is N+1 space
            for (int i = 2; i <= N; i++)//Initialize bool array
            {
                a[i]=true;//Initialize the array through a loop so that its elements are all True
            }
            for (int i = 2; i <= N; i++)//Modify the elements in the array, and assign False if the subscript is not a prime
            {
                for(int j = i * 2; j <= N; j += i)
                {
                    a[j] = false;
                }
            }
            Console.Write("Prime numbers in this range:");
            for (int i = 2; i <= N; i++)//Output a[i]==True array subscript
            {
                if (a[i])
                {
                    Console.Write(i + " ");
                }
            }

        }
    }
}

Operation result:

2. Blocking game

Main points:

  • Array of buttons
  • Button generation, adding, event
  • Tag button
  • Function writing
  • Writing of notes
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        const int N = 4; //Number of rows and columns of buttons
        Button[,] buttons = new Button[N, N]; //Array of buttons


        /**
         * Enter the window, the loading interface is the button
         **/


        private void Form1_Load(object sender, EventArgs e)//Load out after the form is opened
        {
            //Create all buttons
            GenerateAllButtons();//Call create button method
        }

        void GenerateAllButtons()//Create button
        {
            int x = 100, y = 10, w = 45, h = 50;//x. Y stands for the position of the upper left corner, w stands for the length and width of the button, h stands for the rectangle of 50 (button plus 5 borders)
            for (int r = 0; r < N; r++)//Number of button rows
            {
                for (int c = 0; c < N; c++)//Number of button columns
                {
                    int num = r * N + c;
                    Button btn = new Button();
                    btn.Text = (num + 1).ToString();
                    btn.Top = y + r * h;//Position of y in the upper left corner of the button
                    btn.Left = x + c * h;//Position of x in the top left corner of the button
                    btn.Width = w;//Button width
                    btn.Height = w;//Button height
                    btn.Visible = true;//Show it or not
                    btn.Tag = r * N + c; //This data is used to indicate its row and column position


                    //Register events (Tab to insert)
                    btn.Click += new EventHandler(btn_Click);//Create button must register event 

                    buttons[r, c] = btn; //Put in array
                    this.Controls.Add(btn); //Add to interface
                }
            }
             buttons[N - 1, N - 1].Visible = false; //Last invisible
        }

        /**
        * Click the start button to trigger the button to disrupt the function
        **/


        private void Start_Click(object sender, EventArgs e)
        {
            //Scrambling button order
            Shuffle();
        }

        //Scramble button order function
        void Shuffle()
        {
            //Swap two buttons at random many times - actually, the button position remains the same, the text (number) on the swap button and the visibility of the button (Visible)
            Random rnd = new Random();

            for(int i = 0; i < 100; i++)//100 random exchanges
            {
                int a = rnd.Next(N);//Randomly select any row / column in N column / row
                int b = rnd.Next(N);
                int c = rnd.Next(N);
                int d = rnd.Next(N);
                //Swap() exchange function
                Swap(buttons[a, b], buttons[c, d]);//Swap the rows and columns of two buttons - actually, the position of the button remains the same, the text (number) on the button and the visibility of the button (Visible)
            }
        }

        //Button exchange function
        void Swap(Button btn1,Button btn2)
        {
            //Exchange between two button texts
            String t = btn1.Text;//Assign the text of button btn1 to variable t
            btn1.Text = btn2.Text;//Assign the text of button btn2 to btn1
            btn2.Text = t;//The text of btn1 in the variable is given to btn2 to realize the button text exchange

            //Switch visibility of buttons - (switch between an invisible button and a visible button)
            //Whether the value visible is bool type (True) or not (False)
            bool m = btn1.Visible;//Give the visibility of button btn1 to variable m
            btn1.Visible = btn2.Visible;//Give btn2 visibility to btn1
            btn2.Visible = m;//Realize button visibility interchangeability
        }



        /**
         * Click the button around the invisible button in the interface, trigger to exchange the empty button with other buttons, and switch the button order to the front of the confusion
         **/   
         
            
       private void btn_Click(object sender,EventArgs e) //Handling of button click events
        {
            Button btn = sender as Button; //Buttons in current point
            Button blank = FindHiddenButton();//Find blank button

            //Judge whether the currently clicked button is adjacent to the blank button
            if (IsNeighbor(btn, blank)) //If adjacent, swap
            {
                Swap(btn, blank);
                blank.Focus();//Set focus for blank buttons
            }


            //Judge if it's done (adjust it to before disruption)
            if (ResultlsOk())
            {
                MessageBox.Show("Congratulations, the task of block arrangement is completed!");
            }
        }


        //Find (hide) the blank Button (Button type function) Button and return the position of the Button in the Button array
        Button FindHiddenButton()
        {
            //Traverse all buttons to query  
            for (int r = 0; r < N; r++)
            {
                for(int c = 0; c < N; c++)
                {
                    if (!buttons[r, c].Visible)
                    {
                        return buttons[r, c];//Back to blank button
                    }
                }
            }
            return null;
        }

        //Judge whether adjacent
        bool IsNeighbor(Button btna,Button btnb)
        {
            int a = (int)btna.Tag;//Record in Tag is row position
            int b = (int)btnb.Tag;

            int r1 = a / N, c1 = a % N;//r for row, c for column
            int r2 = b / N, c2 = b % N;

            if (r1 == r2 && (c1 == c2 - 1 || c1 == c2 + 1) || c1 == c2 && (r1 == r2 - 1 || r1 == r2 + 1)) //Left and right adjacent (in the same row, the column number is adjacent); up and down adjacent (in the same column, the row number is adjacent)
            {
                return true;//adjacent
            }
            return false;//Non adjacent 
        }


        //Judge whether the inspection is completed
        bool ResultlsOk()
        {
            for (int r = 0; r < N; r++)
            {
                for(int c = 0; c < N; c++)
                {
                    if (buttons[r, c].Text != (r * N + c + 1).ToString())//Check that the location is consistent with its text
                    {
                        return false;//Inconsistent, incomplete
                    }
                }
     
            }
            return true;//Consistent, complete
        }

    }
}

Operation result:


Dream bubble

Published 11 original articles, won praise 0, visited 332
Private letter follow

Posted by dwu on Wed, 12 Feb 2020 07:04:24 -0800