ปัญหา: ลบสมาชิกในอาร์เรย์ตำแหน่งที่ผู้ใช้ระบุ
รับขนาดอาร์เรย์และค่าสมาชิก แล้วลบสมาชิกที่ตำแหน่ง pos (1-based) โดยเลื่อนสมาชิกถัดไปซ้าย 1 ช่อง ถ้าตำแหน่งไม่ถูกต้อง แสดง "Invalid Input"
อัลกอริทึม
- อ่านขนาดอาร์เรย์ n
- จัดสรรหน่วยความจำแบบไดนามิกด้วย
malloc - อ่านค่าสมาชิก n ค่า
- อ่านตำแหน่ง pos ที่ต้องการลบ
- ถ้า pos ≤ n: วนลูปจาก pos-1 ถึง n-2 ก็อปปี้ค่าจาก index ถัดไปมาทับ แล้วพิมพ์ n-1 ค่าที่เหลือ
- มิฉะนั้น พิมพ์ "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