อาร์เรย์คือกลุ่มของรายการข้อมูลที่เกี่ยวข้องซึ่งจัดเก็บด้วยชื่อเดียว
ตัวอย่างเช่น นักเรียน int[30]; //student คือชื่ออาร์เรย์ที่เก็บชุดข้อมูล 30 ชุดโดยใช้ชื่อตัวแปรเดียว
การทำงานของอาร์เรย์
-
กำลังค้นหา − ใช้เพื่อค้นหาว่ามีองค์ประกอบเฉพาะหรือไม่
-
การเรียงลำดับ - ช่วยในการจัดเรียงองค์ประกอบในอาร์เรย์ไม่ว่าจะเป็นจากน้อยไปมากหรือจากมากไปน้อย
-
ขวาง − มันประมวลผลทุกองค์ประกอบในอาร์เรย์ตามลำดับ
-
กำลังแทรก - ช่วยในการแทรกองค์ประกอบในอาร์เรย์
-
กำลังลบ − ช่วยในการลบองค์ประกอบในอาร์เรย์
ตรรกะในการหาเลขคู่ในอาร์เรย์ เป็นดังนี้ −
for(i = 0; i < size; i ++){
if(a[i] % 2 == 0){
even[Ecount] = a[i];
Ecount++;
}
} ตรรกะในการค้นหาเลขคี่ในอาร์เรย์ เป็นดังนี้ −
for(i = 0; i < size; i ++){
if(a[i] % 2 != 0){
odd[Ocount] = a[i];
Ocount++;
}
} เพื่อแสดงเลขคู่ , ฟังก์ชั่นแสดงการโทรตามที่กล่าวไว้ด้านล่าง −
printf("no: of elements comes under even are = %d \n", Ecount);
printf("The elements that are present in an even array is: ");
void display(int a[], int size){
int i;
for(i = 0; i < size; i++){
printf("%d \t ", a[i]);
}
printf("\n");
} เพื่อแสดงเลขคี่ , ฟังก์ชั่นแสดงการโทรตามที่ระบุด้านล่าง −
printf("no: of elements comes under odd are = %d \n", Ocount);
printf("The elements that are present in an odd array is : ");
void display(int a[], int size){
int i;
for(i = 0; i < size; i++){
printf("%d \t ", a[i]);
}
printf("\n");
} โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อแยกเลขคู่และคี่ในอาร์เรย์โดยใช้ for loop -
#include<stdio.h>
void display(int a[], int size);
int main(){
int size, i, a[10], even[20], odd[20];
int Ecount = 0, Ocount = 0;
printf("enter size of array :\n");
scanf("%d", &size);
printf("enter array elements:\n");
for(i = 0; i < size; i++){
scanf("%d", &a[i]);
}
for(i = 0; i < size; i ++){
if(a[i] % 2 == 0){
even[Ecount] = a[i];
Ecount++;
}
else{
odd[Ocount] = a[i];
Ocount++;
}
}
printf("no: of elements comes under even are = %d \n", Ecount);
printf("The elements that are present in an even array is: ");
display(even, Ecount);
printf("no: of elements comes under odd are = %d \n", Ocount);
printf("The elements that are present in an odd array is : ");
display(odd, Ocount);
return 0;
}
void display(int a[], int size){
int i;
for(i = 0; i < size; i++){
printf("%d \t ", a[i]);
}
printf("\n");
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter size of array: 5 enter array elements: 23 45 67 12 34 no: of elements comes under even are = 2 The elements that are present in an even array is: 12 34 no: of elements comes under odd are = 3 The elements that are present in an odd array is : 23 45 67