ตัวแปรอาเรย์ (ARRAY)

1
1846

อาเรย์ คืออะไร

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

ประกาศตัวแปรทั่วไป ประกาศตัวแปรแบบอาร์เรย์
int n1 = 10;
int n2 = -20;
int n3 = 30;
int n4 = 40;
int n5 = 60;
int[] number = {10, -20, 30, 40, 60};



รูปแบบการประกาศค่าตัวแปรอาเรย์

          ชนิดข้อมูล ชื่อตัวแปรอาเรย์[] = {ค่าตัวแปร1, ค่าตัวแปร2, ค่าตัวแปร3,…..ค่าตัวแปรn};

ตัวอย่างการประกาศค่าตัวแปรอาเรย์

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

          string province = {Sukhothai, Pitsanulok, Phichit};


ตัวอย่างการใช้งาน

public class Testarrayy {

     public Testarrayy() {

    }

    public static void main(String[] args) {

        int[] anArray;

        anArray = new int[5];

        anArray[0] = 100;

        anArray[1] = 200;

        anArray[2] = 300;

        anArray[3] = 400;

        anArray[4] = 500;

        System.out.println(“Element at index 0:”+anArray[0]);

        System.out.println(“Element at index 1:”+anArray[1]);

        System.out.println(“Element at index 2:”+anArray[2]);

        System.out.println(“Element at index 3:”+anArray[3]);

        System.out.println(“Element at index 4:”+anArray[4]);

    }

}


ผลลัพธ์โปรแกรม




แบบฝึกหัด

จงเขียนโปรแกรมประกาศตัวแปรอาเรย์ 1 มิติ ชนิด string จำนวน 10 ข้อมูล