The Array Data Type - Kasetsart University



The Array Data Type

The array is a data structure in which we store a collection of data items of the same type (homogeneous elements). By using an array, we can associate a single variable name (for example, score) with the entire collection of data. This association enables us to save the entire collection of data in main memory and to reference individual items easily.

ความหมายของโครงสร้างข้อมูล (data structure) คือตัวแปร 1 ตัว สามารถเก็บค่าได้มากกว่า 1 ค่า และเราสามารถอ้างถึง หรือหยิบค่าที่อยู่ในโครงสร้างมาประมวลผลได้อย่างง่าย ๆ

Array หรือแถวลำดับเป็นโครงสร้างข้อมูล (data structure) ที่มีคุณสมบัติการจัดรูปโครงสร้างไม่แปรปรวนตลอดการทำงานของโปรแกรม อาร์เรย์ประกอบด้วยสมาชิกโดยที่สมาชิกแต่ละตัวในอาร์เรย์ต้องมีคุณสมบัติเหมือนกัน กล่าวคือมีชนิดข้อมูลเป็นแบบเดียวกัน (homogeneous elements)และจำนวนสมาชิกในอาร์เรย์จะไม่มีการเปลี่ยนแปลงตั้งแต่เริ่มต้นจนกระทั่งจบการทำงานของโปรแกรม

ทันที่เราประกาศตัวแปรอาร์เรย์ขึ้นมาใช้งาน คอมไพเลอร์จะจองเนื้อที่ในหน่วยความจำหลักติดต่อกันจำนวนหนึ่งเรียกว่าบล็อก (Block) และแบ่งหน่วยความจำนั้น ออกเป็นช่องๆ เรียกว่า component ซึ่งแต่ละ component มีขนาดเนื้อที่เท่ากัน เช่นถ้าเป็นอาร์เรย์ของ integer ก็จะใช้เนื้อที่ช่องละ 4 bytes เพื่อเก็บค่าสมาชิกแต่ละตัวของอาร์เรย์

เช่น สมมุติให้ score เป็นตัวแปรประเภทอาร์เรย์ ที่มีจำนวนสมาชิก 10 ตัว สมาชิกทั้ง 10 ตัวในอาร์เรย์ score นี้ต้องมีชนิดข้อมูลเป็นแบบเดียวกัน เช่นเป็นประเภท int ทั้งหมด หรือเป็น double ทั้งหมด เป็นต้น ค่าสมาชิกแต่ละตัวจะถูกเก็บไว้ในอาร์เรย์แต่ละช่อง

ตัวอย่างการประกาศตัวแปรอาร์เรย์ (Array Declaration)

Syntax:

( Declaration only

[] ;

← Declaration with creation

[] = new [];

❑ Declaration with initialization: 2 ways

แบบที่ 1 [] = new [] {};

แบบที่ 2 [] = {};

( Declaration only

int [] a;

← Declaration with creation

แบบที่ 1 int [] a;

a = new int[20];

แบบที่ 2 int [] b = new int[20];

❑ Declaration with initialization: 2 ways

แบบที่ 1 int [] c = new int[5] {1,2,3,4,5};

แบบที่ 2 int [] d = {7,8,9,10};

ตัวอย่างการประกาศอาร์เรย์และภาพการจองเนื้อที่ในหน่วยความจำหลัก

1. การประกาศตัวแปรอาร์เรย์เป็น Local Variable เราประกาศภายในเมธอดใดๆ ด้วยรูปแบบการประกาศ

ดังตัวอย่างต่อไปนี้

ตัวอย่างที่ 1

double [] score

score = new double[10]

Compiler reserves a contiguous space called a block (จองเนื้อที่ติดต่อกันจำนวนหนึ่งเรียกว่าบล็อก) in main memory and divides this block into 10 components. Each component has the same size.

|45.2 |51.5 |39.8 |………… |………… |………… |47.8 |

| | | | ….. | ….. | ….. | |

|score[0] |score[1] |score[2] | | | |score[9] |

ตัวแปร score

ตัวอย่างที่ 2

string [] Uname

Uname = new string[5]

|Kasetsart |Chulalongkorn |Thammasat | Chiengmai |Songkhla |

| | | | | |

|Uname[0] |Uname[1] |Uname[2] |Uname[3] |Uname[4] |

ตัวแปร Uname

ตัวอย่างที่ 3

char [] alpha

alpha = new char[5]

|K |A |S | E |T |

| | | | | |

|alpha[0] |alpha[1] |alpha[2] |alpha[3] |alpha[4] |

ตัวแปร alpha

2. การประกาศตัวแปรอาร์เรย์เป็น Global Variable : ตัวแปร array สามารถประกาศเป็น Global Variable

ได้ ถ้าผู้เขียนโปรแกรมต้องการให้ทุกเมธอดสามารถอ้างถึงตัวแปรอาร์เรย์ตัวนี้ได้ การประกาศเป็น Global

Variable ต้องประกาศนอกเมธอดใดๆ และขึ้นต้นการประกาศว่า static มีการประกาศได้ 2 แบบดังนี้

แบบที่ 1

namespace ConsArr1miti

{

class Class1

{

static double [] gradeAVG;

static void Course()

{

gradeAVG[0] = gradeAVG[0] + 9.8;

gradeAVG[1] = gradeAVG[1] + 6.7;

}

static void Subject()

{

gradeAVG[0] = gradeAVG[0] * 5;

gradeAVG[1] = gradeAVG[1] * 5;

}

static void Main(string[] args)

{

gradeAVG = new double[2];

gradeAVG[0] = 1.1;

gradeAVG[1] = 2.1;

Subject();

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]);

Course();

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]);

}

}

}

แบบที่ 2

namespace ConsArr1miti

{

class Class1

{

static double [] gradeAVG = new double[2];

static void Course()

{

gradeAVG[0] = gradeAVG[0] + 9.8;

gradeAVG[1] = gradeAVG[1] + 6.7;

}

static void Subject()

{

gradeAVG[0] = gradeAVG[0] * 5;

gradeAVG[1] = gradeAVG[1] * 5;

}

static void Main(string[] args)

{

gradeAVG[0] = 1.1;

gradeAVG[1] = 2.1;

Subject();

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]); ( (

Course();

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]); ( (

}

}

}

การประกาศอาร์เรย์เป็น Global Variable ต้องระวังเรื่องค่าปัจจุบันของอาร์เรย์ที่จะถูกนำไปประมวลผลอย่างต่อเนื่อง ดังนั้น ผู้เขียนต้องทราบอยู่เสมอว่าค่าในขณะปัจจุบันของตัวแปรเป็นค่าอะไร จากตัวอย่างข้างต้นได้ประกาศอาร์เรย์ gradeAVG เป็น Global Variable ค่าเริ่มต้นของอาร์เรย์ทั้ง 2 ช่องคือ gradeAVG[0] = 1.1;

gradeAVG[1] = 2.1;

ซึ่งค่าทั้งสองจะถูกนำไปประมวลผลในเมธอด Subject() ทำให้ค่า gradeAVG[0] = 1.1 * 5 และ gradeAVG[1] = 2.1 * 5; ดังนั้น ผลลัพธ์ ( คือ 5.5, 10.5

คำสั่งต่อมา เมธอด Main() เรียกใช้เมธอด Course() ภายหลังจากการประมวลผลเมธอด Course() เสร็จแล้ว ทำให้ค่า gradeAVG[0] = 5.5 + 9.8 และ gradeAVG[1] = 10.5 + 6.7; ดังนั้น ผลลัพธ์ ( คือ 15.3, 17.2

ค่าเริ่มต้นของสมาชิกในตัวแปรอาร์เรย์เกิดขึ้นได้อย่างไร

1. การกำหนดค่าเริ่มต้นให้กับอาร์เรย์ในประโยคเดียวกันกับการประกาศตัวแปร ซึ่งถ้าเป็น Global variable ต้องกำหนดไว้นอกเมธอดใด ๆ โดยขึ้นต้นการประกาศว่า static ตามด้วย data type ของสมาชิก, ชื่ออาร์เรย์, และค่าเริ่มต้น

namespace ConsArr1miti1

{

class Class1

{

static double [] gradeAVG = {1.1, 1.2};

static void Main(string[] args)

{

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]);

}

}

}

และถ้าเป็น Local variable ให้ทำการกำหนดภายในเมธอด

namespace ConsArr1miti2

{

class Class1

{

static void Main(string[] args)

{

double [] gradeAVG = {1.1, 1.2};

Console.WriteLine("{0} {1}", gradeAVG[0], gradeAVG[1]);

}

}

}

ตัวอย่างที่

2. การกำหนดค่าเริ่มต้นให้กับอาร์เรย์ โดยการ assign ค่าให้กับสมาชิกแต่ละตัวด้วย assignment statement

class ArrayTest

{

static void Main()

{

int [] score = new int [5];

score[0] = 27;

score[1] = 30;

score[2] = 42;

score[3] = 38;

score[4] = 55;

int total = score[0] + score[1] + score[2] + score[3] + score[4];

double mean = total/5.0;

Console.WriteLine(mean);

}

}

3. การกำหนดค่าเริ่มต้นให้กับอาร์เรย์ด้วย Console.ReadLine() statement

class ArrayTest

{

static void Main()

{

int [] score = new int [5];

score[0] = int.Parse(Console.ReadLine());

score[1] = int.Parse(Console.ReadLine());

score[2] = int.Parse(Console.ReadLine());

score[3] = int.Parse(Console.ReadLine());

score[4] = int.Parse(Console.ReadLine());

int total = score[0] + score[1] + score[2] + score[3] + score[4];

double mean = total/5.0;

Console.WriteLine(mean);

}

}

การอ่านค่าให้กับสมาชิกแต่ละตัวของอาร์เรย์ อาจไม่สะดวกสำหรับถ้าอาร์เรย์ที่มีจำนวนสมาชิกมาก เพราะต้องใช้คำสั่ง Console.ReadLine() หลายครั้ง วิธีที่ดีกว่าคือการใช้คำสั่ง Loop ดังตัวอย่าง

class ArrayTest

{

static void Main()

{

int n = 5;

int [] score = new int [5];

int i; double total = 0, mean;

for (i = 0; i < n; i++)

score[i] = int.Parse(Console.ReadLine());

for (i = 0; i < n; i++)

total += score[i];

mean = total/n;

Console.WriteLine(mean);

}

}

ข้อควรระวังการประกาศ และการอ้างถึงอาร์เรย์

( Array is a reference data type.

class ArrayTest

{

static void Main()

{

int [] score ;

score[1] = 5; ( ERROR

………….;

}

}

( Therefore, before using it, we have to create the array, using the new statement.

class ArrayTest

{

static void Main()

{

int [] score ;

score = new int [10];

score[1] = 5; ( OKAY

………….;

}

}

คำสั่ง Length : We can read the size of the array by access its Length member.

class ArrayTest

{

static void Main()

{

int [] a = new int [5] {1, 2, 3, 4, 5};

Console.WriteLine("A has {0} elements.", a.Length);

for(int i = 0; i < a.Length; i++)

Console.Write ("{0}, ", a[i]);

Console.WriteLine();

a = new int [3] {9, 8, 7}; // we can create the other array

Console.WriteLine("Now a has {0} elements.", a.Length);

for(int i = 0; i < a.Length; i++)

Console.Write("{0}, ", a[i]);

Console.WriteLine();

}

}

คำสั่ง Foreach : คำสั่งเพื่อนำข้อมูลสมาชิกในอาร์เรย์มาใช้งานด้วยวิธีที่ง่ายที่สุด คือการใช้ลูปแบบ foreach

ซึ่งมีรูปแบบการใช้กับอาร์เรย์ดังนี้

class ArrayTest

{

static void Main()

{

int total = 0, k;

int [] score = new int[5];

for (k = 0; k max)

max = score[k];

return (max);

}

24. static void printArr(double [] score)

{

foreach(double k in score)

Console.Write("{0} ",k);

Console.WriteLine();

}

30. static void sortAsc(double [] score)

{

int k, j; double temp;

bool found;

for (k = 1; k=0) && (found == false))

{

if (temp < score[j])

{

score[j+1] = score[j];

j = j-1;

}

else found = true;

}

score[j+1] = temp;

}

}

51. static void Main(string[] args)

{

int k; double maxValue, avgValue;

double [] arr = new double[n];

Console.WriteLine("Input elements into array");

for(k = 0; k < n; k++)

arr[k] = int.Parse(Console.ReadLine());

Console.WriteLine("Display original array : ");

59. printArr(arr);

60. maxValue = maxScore(arr);

61. sortAsc(arr);

Console.WriteLine("Display sorted ascending array");

63. printArr(arr);

64. avgValue = avgArr(arr);

Console.WriteLine("The maximum value = {0}", maxValue);

Console.WriteLine("The average value = {0}", avgValue);

}

}

จากตัวอย่างที่ 2 เป็นการสร้างอาร์เรย์ 1 มิติที่มีขนาด n (n ประกาศเป็นตัวแปร Global ในบรรทัดที่ 5 เพื่อให้ทุกเมธอดอ้างถึงมันได้)

บรรทัดที่ 59 เมธอด Main() เรียกใช้เมธอด printArr() โดยผ่านตัวแปร arr ไปแสดงผล

บรรทัดที่ 60 เมธอด Main() เรียกใช้เมธอด ประเภท function maxScore() เพื่อหาค่าสูงสุดของอาร์เรย์ arr บรรทัดที่ 61 เมธอด Main() เรียกใช้เมธอด sortAsc() โดยผ่านตัวแปร arr ไปเรียงลำดับค่าในอาร์เรย์จากน้อยไปมาก การส่งพารามิเตอร์ arr ไปนี้ จะ Pass By Reference ไปก็ได้ ซึ่งบรรทัดที่ 30 ก็ต้องรับแบบ ref ด้วย แต่ไม่ว่าจะ Pass ref หรือ Pass value ก็ให้ผลเหมือนกัน คือส่งอาร์เรย์ที่เปลี่ยนแปลงแล้วกลับคืนเมธอด Main() ดังนั้นในบรรทัดที่ 63 เพื่อมีการเรียกเมธอด printArr() อีกครั้ง จึงแสดงผลจึงเป็นอาร์เรย์ที่ sort แล้ว

Case ที่ควรระวัง และต้องทำความเข้าใจ

***** พิจารณาโปรแกรมต่อไปนี้ ทำความเข้าใจกับประโยคคำสั่งที่ 6 ******

การผ่านตัวแปรอาร์เรย์จากเมธอด Main() ไปยังเมธอด ChangeArr() ของตัวอย่างโปรแกรมในกรอบเป็นแบบ Pass By Value และภายในเมธอด ChangeArr() บรรทัดที่ 6 เป็นประโยคที่ขอให้คอมไพเลอร์จัดสรรเนื้อที่ใหม่ให้ ซึ่งเป็นเนื้อที่ที่จะถูกสร้างขึ้นใหม่ภายในขอบเขตของเมธอด ChangeArr()

1

4

5

Display at ChangeArr()

0

0

0

After Calling ChangeArr()

1

4

5

ถ้านำโปรแกรมในกรอบข้างต้นมาเปลี่นการผ่านพารามิเตอร์อาร์เรย์ให้เป็นแบบ Pass By Reference

***** พิจารณาโปรแกรมต่อไปนี้ ทำความเข้าใจ

การผ่านตัวแปรอาร์เรย์จากเมธอด Main() ไปยังเมธอด ChangeArr() ของตัวอย่างโปรแกรมในกรอบนี้เป็นแบบ Pass By Reference และภายในเมธอด ChangeArr() บรรทัดที่ 6 เป็นประโยคที่ขอให้คอมไพเลอร์จัดสรรเนื้อที่บริเวณเดิมให้ใหม่ ภายในขอบเขตของเมธอด Main()

1

4

5

Display at ChangeArr()

0

0

0

After Calling ChangeArr()

0

0

0

อาร์เรย์ 2 มิติ (Two Dimensional Array)

Two Dimensional Array, the most common multidimensional array is used to store information that we normally represent in a table form. For example, 3 subject scores of 4 students.

| | English | Drawing | Calculus I |

|Mollapak | 75.50 | 35.50 | 45.62 |

|Pongrit | 50.00 | 40.00 | 53.30 |

|Panita | 72.80 | 32.00 | 48.00 |

|Attasuda | 68.58 | 38.50 | 47.30 |

Array of 4 rows x 3 columns

In order to reference to any specific element of the two dimensional array, 2 indices must be used. One index is used to specify the row and the other index is used to specify the column. For example, if we declare a variable arr to be a two dimensional array, arr[2, 3] means the element of array

arr at the component row 3 and column 4.

การประกาศตัวแปร 2 มิติ

namespace ConsArr1Miti_Sort

{

class ClassArr2Miti

{

static void Main()

{

int [,] pc = new int [3,5];

for (int k = 0; k st2 (หรือ st1 < st2) ได้ เพราะจะเกิด syntax error แต่ให้ใช้คำสั่ง CompareTo แทน ซึ่งมีรูปแบบการใช้ดังนี้

namespace ConsArr2Miti_String

{

class Class1

{

static void Main(string[] args)

{

string st1 = "aaa";

string st2 = "bbb";

int result;

result = (pareTo (st2));

Console.WriteLine(result);

}

}

}

ตัวแปร result จะมีค่า -1 ถ้า st1 < st2 และมีค่าเป็น 0 ถ้า st1 == st2 และมีค่า 1 ถ้า st1 > st2

-----------------------

double [] score = new double [10];

string [] Uname = new string [5];

char [] alpha = new char[5];

ต้องลบ 1 ออกเพราะลำดับสมาชิกในอาเรย์เริ่มจาก 0 เสมอ ดังนั้นลำดับของสมาชิกตัวที่ 3 คือ 2

int [] score = new int [10];

foreach (datatype variable in ArrayName)

{

………………………;

}

foreach

can only retrieve

elements in arrays

การอ่านค่าให้กับ array ต้องใช้ for loop ใช้ foreach ไม่ได้ เพราะ foreach เป็นคำสั่งที่นำค่าสมาชิกมาใช้งาน

class ClassSort

{

static void Main(string[] args)

{

int n = 5, k, temp, j;

bool found;

int [] arrSort = new int[n];

Console.WriteLine("Input elements into array");

for(k = 0; k < n; k++)

arrSort[k] = int.Parse(Console.ReadLine());

for (k = 1; k=0) && (found == false))

{

if (temp < arrSort[j])

{

arrSort[j+1] = arrSort[j];

j = j-1;

}

else found = true;

}

arrSort[j+1] = temp;

}

Console.WriteLine("Output of sorted array");

for(k = 0; k < n; k++)

Console.Write("{0} ",arrSort[k]);

Console.WriteLine();

}

}

}

Array.Sort (ArrayName) หรือ

Array.Sort (ArrayName, StartIndex, Length)

Array.Reverse (ArrayName) หรือ

Array.Reverse (ArrayName, StartIndex, Length)

บรรทัดที่ 16, 17

บรรทัดที่ 8, 9, 10

บรรทัดที่ 19, 20, 21

1. class Class1

2. {

3. static void ChangeArr(int [] arr,int n)

4. {

5. int k;

6. arr = new int[n];

7. for (k = 0; k < n; k++)

8. arr[k] = arr[k] * 2;

9. Console.WriteLine("Display at ChangeArr()");

10. for (k = 0; k < n; k++)

11. Console.WriteLine(arr[k]);

12. }

13. static void Main(string[] args)

14. {

15. const int n = 3;

16. int [] myArray = new int[n]{1,4,5};

17. foreach(int k in myArray)

18. Console.WriteLine(k);

19. ChangeArr(myArray,n);

20. Console.WriteLine("After Calling ChangeArr()");

21. foreach(int k in myArray)

22. Console.WriteLine(k);

23. }

24. }

บรรทัดที่ 17, 18

บรรทัดที่ 9, 10, 11

บรรทัดที่ 20, 21, 22

1. class Class1

2. {

3. static void ChangeArr(ref int [] arr,int n)

4. {

5. int k;

6. arr = new int[n];

7. for (k = 0; k < n; k++)

8. arr[k] = arr[k] * 2;

9. Console.WriteLine("Display at ChangeArr()");

10. for (k = 0; k < n; k++)

11. Console.WriteLine(arr[k]);

12. }

13. static void Main(string[] args)

14. {

15. const int n = 3;

16. int [] myArray = new int[n]{1,4,5};

17. foreach(int k in myArray)

18. Console.WriteLine(k);

19. ChangeArr(ref myArray,n);

20. Console.WriteLine("After Calling ChangeArr()");

21. foreach(int k in myArray)

22. Console.WriteLine(k);

23. }

24. }

บรรทัดที่ 17, 18

บรรทัดที่ 9, 10, 11

บรรทัดที่ 20, 21, 22

arr [1, 2]

arr [3, 0]

For (k = 0; k < person.Length; k++)

person[k] = Convert.Tochar(Console.ReadLine());

double [,] score = new double [3,4];

string [] Uname = new string [4,2];

char [] alpha = new char[2,5];

หรือ

string [,] stName = new stName[2,3]{{"TU", "KU", "AIT"},

{"CU", "KKU", "MU"}};

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download