Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ค้นหาสมาชิกในอาร์เรย์ด้วย Pointers

โจทย์

เขียนโปรแกรม C ค้นหาสมาชิกในอาร์เรย์ที่ผู้ใช้ป้อนตอนรันไทม์ แสดงผลลัพธ์ ถ้าไม่พบแสดง "not found"

วิธีแก้

อาร์เรย์เก็บกลุ่มข้อมูลร่วมชื่อเดียวกัน การดำเนินการ: Insert, Delete, Search

อัลกอริทึม

ขั้นตอน 1 - ประกาศและอ่านจำนวนสมาชิก

ขั้นตอน 2 - ประกาศและอ่านขนาดอาร์เรย์

ขั้นตอน 3 - ป้อนสมาชิกอาร์เรย์

ขั้นตอน 4 - ประกาศตัวแปร pointer

ขั้นตอน 5 - จัดสรรหน่วยความจำไดนามิก

ขั้นตอน 6 - ป้อนค่าที่จะค้นหา

ขั้นตอน 7 - ตรวจสอบว่ามีในอาร์เรย์หรือไม่ ถ้ามีแสดง "Yes" ไม่มี "No"

ตัวอย่าง

ขนาดอาร์เรย์: 5 สมาชิก: 1 2 3 4 5 ค้นหา: 4

Output: 4 is present in the array

โปรแกรม

โปรแกรม C ค้นหาสมาชิกในอาร์เรย์ด้วย Pointers:

#include<stdio.h> int i,l; int search(int ,int *,int); int main(){    int n,m;    printf("enter the size of array:");    scanf("%d",&n);    int a[n];    printf("enter the elements:\n");    for(i=0;i<n;i++){       scanf("%d",&a[i]);    }    printf("enter the element to be searched:");    scanf("%d",&m);    search(n,a,m);    return 0; } int search(int n,int *a,int m){    for(i=0;i<n;i++){       if(m==a[i]){          l=1;          break;       }    }    if(l==1){       printf("%d is present in the array",m);    } else {       printf("%d is not present in the array",m);    } }

ผลลัพธ์

Run 1: enter the size of array:5 enter the elements: 14 12 11 45 23 enter the element to be searched:11 11 is present in the array Run 2: enter the size of array:3 enter the elements: 12 13 14 enter the element to be searched:45 45 is not present in the array