C#代写-EXAMPLE 1:
时间:2021-03-05
Prepared by: Goran Svenk Page 1

4. ARRAYS IN C#
- Reference type in C#

SINGLE-DIMENSIONAL ARRAYS
EXAMPLE 1:
int[] array1 = {2,5,7,1,0,-1,9};
float[] array2 = new float[size2];


EXAMPLE 2:
public partial class Form1 : Form
{
int[] numbers; //array reference

public Form1()
{
InitializeComponent();
}

private void btnArrays_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(textBox1.Text);
numbers = new int[n]; //creates array
Random rnd = new Random();
for (int i = 0; i < n;i++)
{
numbers[i] = rnd.Next(1, 11); //random number 1-10
}
Array.Sort(numbers); //sorts array in ascending order
Array.Reverse(numbers); //reverses order

foreach (int x in numbers) //a new loop in C#
listBox1.Items.Add(x);
}
}


Prepared by: Goran Svenk Page 2

EXAMPLE 3:

using System.Windows.Forms;
using Microsoft.VisualBasic;
//right click project name and ADD REFERENCE: Microsoft Visual Basic

namespace arrays1
{
public partial class Form1 : Form
{
int[] scores; //array reference
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

int x = Convert.ToInt32(Interaction.InputBox(
"How many scores =>", "Number of scores"));

scores = new int[x];
for(int i=0;i scores[i]=Convert.ToInt32(Interaction.InputBox(
"score "+ (i+1)+" => ","Scores"));
Array.Sort(scores);
Array.Reverse(scores);
listBox1.Items.Add("Sorted scores =>");

foreach (int i in scores)
listBox1.Items.Add(i);
}
}
}

MULTIDIMENSIONAL ARRAYS
EXAMPLE 4:
int [,,]a1;
int [][][]a2;
Prepared by: Goran Svenk Page 3

TWO-DIMENSIONAL ARRAYS

1. Regular/Rectangular arrays
2. Jagged arrays

EXAMPLE 5:

namespace TwoDArrays
{
public partial class Form1 : Form
{
int[,] arr1; //rectangular array
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
int r = 3, c = 5;
arr1 = new int[r, c];
Random rnd = new Random();
for (int i = 0; i < r; i++)
{
listBox1.Items.Add("Row: " + (i + 1));
for (int j = 0; j < c; j++)
{
arr1[i, j] = rnd.Next(1, 10);
listBox1.Items.Add(arr1[i, j]);
}
}
}
}
}

NOTE: TableLayoutPanel control, or ListView are
recommended for two-dimensional arrays output.






Prepared by: Goran Svenk Page 4

JAGGED ARRAYS

- Number of columns in each row could be different (i.e. a variable number
of columns)

EXAMPLE 6:

public partial class Form1 : Form
{
int[][] scores; //jagged array
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
int nplayers = 3, ngames;
scores = new int[nplayers][]; //creates row references
Random rnd = new Random();
for (int i = 0; i < nplayers; i++)
{
ngames = rnd.Next(1, 6);
scores[i] = new int[ngames]; //creates columns
for (int j = 0; j < ngames; j++)
{
scores[i][j] = rnd.Next(0, 10); //initializes array
}
}
int cnt=1;

foreach (int[] xrow in scores)
{
listBox1.Items.Add("Player " + cnt + " scores:");
foreach (int x in xrow)
listBox1.Items.Add(x);
cnt++;
}

}
}


essay、essay代写