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

โปรแกรม C ลบสมาชิกอาร์เรย์ด้วย Pointers

ปัญหา: ลบสมาชิกในอาร์เรย์ตำแหน่งที่ผู้ใช้ระบุ

รับขนาดอาร์เรย์และค่าสมาชิก แล้วลบสมาชิกที่ตำแหน่ง pos (1-based) โดยเลื่อนสมาชิกถัดไปซ้าย 1 ช่อง ถ้าตำแหน่งไม่ถูกต้อง แสดง "Invalid Input"

อัลกอริทึม

  1. อ่านขนาดอาร์เรย์ n
  2. จัดสรรหน่วยความจำแบบไดนามิกด้วย malloc
  3. อ่านค่าสมาชิก n ค่า
  4. อ่านตำแหน่ง pos ที่ต้องการลบ
  5. ถ้า pos ≤ n: วนลูปจาก pos-1 ถึง n-2 ก็อปปี้ค่าจาก index ถัดไปมาทับ แล้วพิมพ์ n-1 ค่าที่เหลือ
  6. มิฉะนั้น พิมพ์ "Invalid Input"

โค้ด C

#include <stdio.h>
#include <stdlib.h>

void delete(int n, int *a, int pos) {
    int i, j;
    if (pos <= n) {
        for (i = pos - 1; i < n; i++) {
            j = i + 1;
            *(a + i) = *(a + j);
        }
        printf("after deletion the array elements is:\n");
        for (i = 0; i < n - 1; i++) {
            printf("%d\n", *(a + i));
        }
    } else {
        printf("Invalid Input");
    }
}

int main() {
    int *a, n, i, pos;
    printf("enter the size of array: ");
    scanf("%d", &n);
    a = (int*)malloc(sizeof(int) * n);
    printf("enter the elements:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", (a + i));
    }
    printf("enter the position of element to be deleted: ");
    scanf("%d", &pos);
    delete(n, a, pos);
    return 0;
}

ตัวอย่าง Output

enter the size of array: 5
enter the elements:
12 34 56 67 78
enter the position of element to be deleted: 4
After deletion the array elements are:
12
34
56
78