用C语言编写在数组中插入一个元素
时间: 2024-05-07 10:18:07 浏览: 18
可以通过以下代码在数组中插入一个元素:
```c
#include <stdio.h>
int main() {
int arr[100], n, pos, val;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the position where you want to insert the element: ");
scanf("%d", &pos);
printf("Enter the value of the element you want to insert: ");
scanf("%d", &val);
// Shift elements to the right
for(int i=n-1; i>=pos-1; i--) {
arr[i+1] = arr[i];
}
// Insert element at given position
arr[pos-1] = val;
printf("Array after insertion: ");
for(int i=0; i<=n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
在上面的代码中,我们首先从用户获取数组的大小和元素,然后获取要插入元素的位置和值。我们使用一个循环将数组中的元素向右移动,以便为要插入的元素留出空间。然后,我们将要插入的元素插入到指定的位置,并打印数组。