Computer >> Máy Tính >  >> Lập trình >> lập trình C

Chèn các phần tử vào một mảng bằng Ngôn ngữ C

Chúng ta có thể chèn các phần tử vào bất cứ nơi nào chúng ta muốn, có nghĩa là chúng ta có thể chèn ở vị trí bắt đầu hoặc ở giữa hoặc cuối cùng hoặc bất kỳ đâu trong mảng.

Sau khi chèn phần tử vào mảng, vị trí hoặc vị trí chỉ mục được tăng lên nhưng không có nghĩa là kích thước của mảng tăng lên.

Logic được sử dụng để chèn phần tử là -

  • Nhập kích thước của mảng

  • Nhập vị trí bạn muốn chèn phần tử

  • Tiếp theo, nhập số bạn muốn chèn vào vị trí đó

for(i=size-1;i>=pos-1;i--)
   student[i+1]=student[i];
   student[pos-1]= value;

Mảng cuối cùng sẽ được in bằng vòng lặp for.

Chương trình

#include<stdio.h>
int main(){
   int student[40],pos,i,size,value;
   printf("enter no of elements in array of students:");
   scanf("%d",&size);
   printf("enter %d elements are:\n",size);
   for(i=0;i<size;i++)
      scanf("%d",&student[i]);
   printf("enter the position where you want to insert the element:");
   scanf("%d",&pos);
   printf("enter the value into that poition:");
   scanf("%d",&value);
   for(i=size-1;i>=pos-1;i--)
      student[i+1]=student[i];
   student[pos-1]= value;
   printf("final array after inserting the value is\n");
   for(i=0;i<=size;i++)
      printf("%d\n",student[i]);
   return 0;
}

Đầu ra

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 poition:48
final array after inserting the value is
12
23
48
34
45
56
67