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

การแทรกข้อมูลในอาร์เรย์ (Array Insertion) ในภาษา C


แทรกข้อมูลใน Array ได้ที่ตำแหน่งไหนก็ได้: เริ่มต้น, กลาง, หรือท้าย หลังแทรก Index จะเลื่อน แต่ขนาด Array ไม่เปลี่ยน

ตรรกะการแทรก

  1. รับขนาด Array, ตำแหน่งที่จะแทรก (pos), ค่าที่จะแทรก (value)
  2. เลื่อนข้อมูลจากท้ายมาหน้า: for(i=size-1; i>=pos-1; i--) a[i+1] = a[i];
  3. วางค่าใหม่: a[pos-1] = value;

โปรแกรมตัวอย่าง

#include <stdio.h>
int main() {
    int arr[40], pos, size, value, i;
    
    printf("Array size: ");
    scanf("%d", &size);
    printf("Enter %d elements: ", size);
    for(i = 0; i < size; i++) scanf("%d", &arr[i]);
    
    printf("Insert position (1-%d): ", size+1);
    scanf("%d", &pos);
    printf("Value to insert: ");
    scanf("%d", &value);
    
    // Shift right
    for(i = size - 1; i >= pos - 1; i--)
        arr[i+1] = arr[i];
    
    arr[pos-1] = value;
    
    printf("Array after insert:\n");
    for(i = 0; i <= size; i++) printf("%d\n", arr[i]);
    return 0;
}

ผลลัพธ์

enter no of elements in array of students: 6
enter 6 elements are: 12 23 34 45 56 67
enter the position where you want to insert the element: 3
enter the value into that position: 48
final array after inserting the value is
12
23
48
34
45
56
67