โจทย์
เขียนโปรแกรม C ตรวจสอบประเภทอาร์เรย์ ว่าสมาชิกเป็นเลขคู่ทั้งหมด เลขคี่ทั้งหมด หรือผสม โดยใช้ pointers
วิธีแก้
ผู้ใช้ป้อนอาร์เรย์จำนวนเต็ม แสดงประเภทอาร์เรย์
ตัวอย่าง 1 - Input: 5 3 1 → Output: odd array
ตัวอย่าง 2 - Input: 2 4 6 8 → Output: even array
ตัวอย่าง 3 - Input: 1 2 3 4 5 → Output: mixed array
อัลกอริทึม
ขั้นตอน 1: อ่านขนาดอาร์เรย์
ขั้นตอน 2: ป้อนสมาชิกอาร์เรย์
ขั้นตอน 3: ประกาศตัวแปร pointer
ขั้นตอน 4: ตรวจสอบสมาชิกทั้งหมดเป็นคี่ด้วย pointer → พิมพ์ "Odd"
ขั้นตอน 5: ตรวจสอบสมาชิกทั้งหมดเป็นคู่ด้วย pointer → พิมพ์ "Even"
ขั้นตอน 6: ไม่เช่นนั้น → พิมพ์ "Mixed"
ตัวอย่าง
โปรแกรม C ตรวจสอบประเภทอาร์เรย์ด้วย pointers:
#include<stdio.h> #include<stdlib.h> int*createArray (int); void readArray(int,int *); int findType(int , int *); int main(){ int *a,n,c=0,d=0; printf("Enter the size of array\n"); scanf("%d",&n); printf("Enter the elements of array\n"); createArray(n); readArray(n,a); findType(n,a); return 0; } int *createArray(int n){ int *a; a=(int*)malloc(n*sizeof(int)); return a; } void readArray(int n,int *a){ for(int i=0;i<n;i++){ scanf("%d",a+i); }} int findType(int n, int *a){ int c=0,d=0; for(int i=0;i<n;i++){ if(a[i]%2==0){ c++; } else{ d++; }} if(c==n){ printf("The array type is Even\n"); } if(d==n){ printf("The array type is Odd\n"); } if(c!=n && d!=n){ printf("The array type is Mixed\n"); } return 0; }
ผลลัพธ์
Enter the size of array 4 Enter the elements of array 12 14 16 18 The array type is Even