Viết chương trình C để thêm 1 phần tử mảng vào 1 vị trí bất kỳ

Các bước thực hiện để viết chương trình C:

1. Nhập vào kích thước của mảng size

2. Nhập vào các phần tử mảng

3. Nhập vào phần tử muốn thêm và vị trí muốn thêm phân tử pos

4. Kiểm tra nếu vị trí pos > kích thước phần tử size hoặc pos < 0 thì thông báo không hợp lệ

5. Nếu vị trí pos <=size+1 thì chèn phần tử vào vị trí pos bằng cách dịch chuyển các phần tử sang bên phải. Sau đó thêm phần tử vào vị trí pos-1 (vì mảng chạy từ 0) và tăng size lên 1 (vì chèn thêm 1 phần tử)

6. In ra mảng sau khi chèn phần tử

Code tham khảo của chương trình C:

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE];
int i, size, num, pos;

/*1. Input size of the array */
printf("Enter size of the array : ");
scanf("%d", &size);

/*2. Input elements in array */
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

/*3. Input new element and position to insert */
printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &pos);

/*4. If position of element is not valid */
if(pos > size+1 || pos <= 0)
{
printf("Invalid position! Please enter position between 1 to %d", size);
}
else/*5. Insert element*/
{
/*5.1. Make room for new array element by shifting to right */
for(i=size; i>=pos; i--)
{
arr[i] = arr[i-1];
}
/*5.2. Insert new element at given position and increment size */
arr[pos-1] = num;
size++;

/*6. Print array after insert operation */
printf("Array elements after insertion : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}

return 0;
}